ABOUT ME

Today
Yesterday
Total
  • Custom Decorators
    Node.js/Nest 2023. 12. 8. 17:29

    Nest.js의 Custom Decorators에 대해 정리하였습니다.



    < Param decorators >

    You can create your own custom decorators.

     

    Ex : @User( ) decorator

    In the node.js world, it's common practice to attach properties to the request object. Then you manually extract them in each route handler, using code like the following:

    const user = req.user;

     

    In order to make your code more readable and transparent, you can create a @User() decorator and reuse it across all of your controllers.

    import { createParamDecorator, ExecutionContext } from '@nestjs/common';
    
    export const User = createParamDecorator(
      (data: unknown, ctx: ExecutionContext) => {
        const request = ctx.switchToHttp().getRequest();
        return request.user;
      },
    );
    @Get()
    async findOne(@User() user: UserEntity) {
      console.log(user);
    }

     

     


    < Passing data >

    you can use the  data  parameter to pass an argument to the decorator's factory function. One use case for this is a custom decorator that extracts properties from the request object by key.

     

    Ex)

    {
      "id": 101,
      "firstName": "Alan",
      "lastName": "Turing",
      "email": "alan@email.com",
      "roles": ["admin"]
    }
    import { createParamDecorator, ExecutionContext } from '@nestjs/common';
    
    export const User = createParamDecorator(
      (data: string, ctx: ExecutionContext) => {
        const request = ctx.switchToHttp().getRequest();
        const user = request.user;
    
        return data ? user?.[data] : user;
      },
    );
    @Get()
    async findOne(@User('firstName') firstName: string) {
      console.log(`Hello ${firstName}`);
    }

     

     


    < Working with pipes >

    Nest treats custom param decorators in the same fashion as the built-in ones ( @Body()  @Param()   and  @Query() ). This means that pipes are executed for the custom annotated parameters as well

     

    Ex)

    @Get()
    async findOne(
      @User(new ValidationPipe({ validateCustomDecorators: true }))
      user: UserEntity,
    ) {
      console.log(user);
    }

    Note that validateCustomDecorators option must be set to trueValidationPipe does not validate arguments annotated with the custom decorators by default.

     

     


    < Decorator composition >

    Nest provides a helper method to compose multiple decorators.

     

    Ex)

    import { applyDecorators } from '@nestjs/common';
    
    export function Auth(...roles: Role[]) {
      return applyDecorators(
        SetMetadata('roles', roles),
        UseGuards(AuthGuard, RolesGuard),
        ApiBearerAuth(),
        ApiUnauthorizedResponse({ description: 'Unauthorized' }),
      );
    }
    @Get('users')
    @Auth('admin')
    findAllUsers() {}

     

     


    Reference : https://docs.nestjs.com/custom-decorators

     

    Documentation | NestJS - A progressive Node.js framework

    Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

    docs.nestjs.com

     

     

     

     

    'Node.js > Nest' 카테고리의 다른 글

    Guards  (0) 2023.11.21
    Pipes  (0) 2023.11.13
    Exception Filters  (0) 2023.10.30
    Middlewares  (0) 2023.10.18
    Modules  (0) 2023.09.26

    댓글

Designed by Tistory.