Create an API via NestJS
November 9, 2019

Create an API via NestJS Part II

Create CRUD

Create infrastructure files:

Via NestCLI generate:

  1. Module: nest g mo quiz
  2. Controller: nest g controller quiz
  3. Service: nest g service quiz/quiz
Where `quiz` is the name of your module.

Setup API controller

1. Open quiz.controller.ts and write some CRUD methods:

You should have something like this

quiz.controller.ts

2. Open quiz.module.ts and import our TypeORM Model:

quiz.module.ts

3. Open quiz.service.ts and add our Entity Repository:

quiz.service.ts

Implement CRUD methods

Now we can implement our CRUD methods, that we had been initialized before. Let's open quiz.service.ts file and write implementation:

quiz.service.ts

As we can see in lines 16 and 20 we use the data param with type any. That is not accorded to TypeScript guidelines, we must write DTO (Data Transfer Object) to tipizate this param:

Create DTO

Firstly we have to create this file via command: touch src/quiz/quiz.dto.ts

Then open this file and describe our data:

quiz.dto.ts

Now we can type param data in quiz.service.ts:

quiz.service.ts

Connect the service to the controller

Now, finally, we can connect our service to the controller. Open quiz.controller.ts and determinate service functions:

quiz.controller.ts

Finally, you can start your server and test its functionality

Test

Actually, we must write many tests and mutch documentation for something like Swagger to our API, but not today. In this part, Postman is enough for us. Let's install it:

sudo snap install postman 

In the Postman press "New" button:

On the next step choose "Request":

Next, setup Name for request and Name for collection, and press Save to Collection:

GET readAll()

Finally, we can create our first request:

  1. Choose type GET
  2. Write address for entry point with format IP : PORT / service
  3. Press Send

If everything is alright, you should see the empty array in the response

POST create()

Change Type to POST and create some entry:

  1. Change Type of Request
  2. Go to tab "Body"
  3. Choose "raw" type
  4. Set "JSON" format
  5. Write your request data. Fields for body you can find in DTO or Entry files

Press Send. And you should see a response like this:

Copy id value, it will be necessary for the next request

PUT update()

Change Type to PUT and edit our entry:

  1. Change Type to PUT
  2. Change URL according to format URL : PORT / SERVICE / UUID
  3. Edit Body data

Press Send. Now response will be different:

DELETE delete()

Change type to DELETE

  1. Change Type to DELETE and press Send

The response should be: