DEV Community

Cover image for Building CRUD API with NestJs - Write First API.
Rasool Khan
Rasool Khan

Posted on • Edited on

Building CRUD API with NestJs - Write First API.

Part II

In Part I, we created nestjs project and created a database and then integrated Mikro-Orm. In this part we are going to create entities and start writing APIs.

We are first going to start with User module. We are going to structure our project like user folder will contain controller, service, repository, entities of it's own and after this module is completed we are going to export this module to our main module i.e. "app.module.ts file".
First, let's create a "user" named folder in src directory.

Create an Entity

Now, let's create a folder "entities" which will contain all the entities related to user.

  1. Here we used @Entity to define an entity. The entity contains many properties and these properties can be defined with either @Property(), @ManyToOne(), @OneToMany(), etc. These are known as decorators, to know more about these checkout out Decorator Reference.

  2. There are also some optional properties like defining an entity property as nullable using @Property({ nullable: true }) and also setting a default value for a property. Check out Defining Entities to know more about how to define an entity and its properties.

  3. We have also used 'class-validator' package which is used to validate an entity property itself. @IsEmail() decorator will check if the email is valid or not. We can add a lot these validation at entity creation level itself so that no improper data reaches the database.

Now let's create user repository. Create this file in the user directory itself.



//user.repository.ts
import { EntityRepository, Repository } from '@mikro-orm/core';
import { User } from './entities/user.entity';

@Repository(User)
export class UserRepository extends EntityRepository<User> {}


Enter fullscreen mode Exit fullscreen mode

Now we need to run migration and apply the migration to create this user table in our database.
Run this command npx mikro-orm migration:create to create a new migration file. If any new entity is created or a change has been made to the existing entities, a new migration file will be generated. Then, npx mikro-orm migration:up command will apply the changes to the database.

Check out these other Mikroorm related commands:



npx mikro-orm migration:create   # Create new migration with current schema diff
npx mikro-orm migration:up       # Migrate up to the latest version
npx mikro-orm migration:down     # Migrate one step down
npx mikro-orm migration:list     # List all executed migrations
npx mikro-orm migration:pending  # List all pending migrations


Enter fullscreen mode Exit fullscreen mode



This is the migration file that is being generated. After applying these changes to the database a new table will be created.

User table

User table columns

First API

Now that our table is created we can start writing APIs. We will create a controller and a service file. Controller file will handle all our APIs related to user and all the business logic will be written in service file.

Controller

We will create a CreateUser API. This API will accept user details and then store it in our user table. First, we need to create a DTO(Data Transfer Object), in simple words DTOs are used to map objects to domain models.
In user directory create "dtos" folder and inside it create "create-user.dto.ts" file.

Here, we have defined all the properties needed to create a new user. As mentioned in previous post to validate a property we are using 'class-validator' library.

Now we can create user controller file.

We are injecting UserService here, where we will call database to perform CRUD operation. In controller, we just handle the incoming request and then send the response back to the client.

Service

UserService is where we make the database call using ORM to store or retrieve the data. Services in Nestjs are known as Providers. Providers (services, repositories, helpers, etc.) can be injected as dependencies.

  1. As repositories are also providers these can be injected as dependency too and we inject UserRepository so that UserService can retrieve or store data in the database.

  2. We have a single method inside user service, which first checks if the a user with given email Id is already stored in database or not. Then, we create a User object using the constructor created in user entity. At last, we save the new user object in the database.

Before, we test our API as mentioned earlier, we need to import this user module in our main "app.module.ts" file. Just add the "UserModule" file in imports.

Test the API.

Run the "npm run start" or "npm run start:dev" command in the terminal to start the application.
For testing we are using Postman, you can download if you don't have it already or you can use postman online in your browser too.

We send a POST request to the /api/user endpoint:
API testing using Postman

After successful response we have our first entry in the database.
Database

Summary

In this tutorial, we created our first API and learned how to uses Mikro-Orm to store and retrieve data from database. And tested our API with postman.

Github Repository - https://github.com/rskhan167/movie-review

That's all for this part see you in the next one. Thanks for reading.
Please Like it and Share with your friends if you found it useful.

Top comments (1)

Collapse
 
felixmutships profile image
FelixMutships

I don't see where you defined dto rtaht you're using. Could you be more clear about that please?