First Controller

The Controllers layer is responsible for handling incoming HTTP requests. In Nest, Controller is a simple class with @Controller() decorator.

In previuos section we set up entry point for an application. Now, let's build our first endpoint /users:

import { Controller, Get, Post, HttpStatus } from '@nestjs/common';

@Controller()
export class UsersController {
    @Get('users')
    getAllUsers() {}

    @Get('users/:id')
    getUser() {}

    @Post('users')
    addUser() {}
}

As you can guess, we created an endpoint with 3 different paths:

GET: users
GET: users/:id 
POST: users

It is not necessary to repeat 'users' in each path.

Nest allows us to pass additional metadata to @Controller() decorator. The path, which is a prefix for each route. Let's rewrite our controller:

import { Controller, Get, Post, HttpStatus } from '@nestjs/common';

@Controller('users')
export class UsersController {
    @Get()
    getAllUsers() {}

    @Get('/:id')
    getUser() {}

    @Post()
    addUser() {}
}

Routes

Let's stop for a while. We setup routes, but they are not doing anything. We don't have any persistence, so we also do not have any user. What's now?

For explanation purposes, I will use a fake data:

@Get()
getAllUsers(req, res, next) {
    res.status(HttpStatus.OK).json([{
        id: 1, name: 'Test'
    }]);
}

As you can see, methods in Nest controllers have the same behaviour as a simple routes in Express.

If you want to learn more about req (request), res (response) and next you should read short Express Routing - Documentation. In Nest, they work equivalently. Furthermore, you can use @types/express package:

import { Request, Response, NextFunction } from 'express';

@Controller('users')
export class UsersController {
    @Get()
    getAllUsers(req: Request, res: Response, next: NextFunction) {}
}

Moreover, Nest provides a set of custom decorators, which you can use to mark arguments.

Nest Express
@Request() / @Req() req
@Response() / @Res() res
@Next() next
@Session() req.session
@Param(param?: string) req.params[param]
@Body(param?: string) req.body[param]
@Query(param?: string) req.query[param]
@Headers(param?: string) req.headers[param]

This is how you can use them:

@Get('/:id')
public async getUser(@Response() res, @Param('id') id) {
    const user = await this.usersService.getUser(id);
    res.status(HttpStatus.OK).json(user);
}

Remember to import decorators at the beginning of a file:

import { Response, Param } from '@nestjs/common';

Important! If you want to use:

Last Step

UsersController is ready to use, but our module doesn't know about it yet. Let's open ApplicationModule and add some metadata.

import { Module } from '@nestjs/common';
import { UsersController } from "./users.controller";

@Module({
    controllers: [ UsersController ]
})
export class ApplicationModule {}

As you can see - we only have to insert our controller into controllers array. It's everything.

results matching ""

    No results matching ""