Dmytro Mysak
Dmytro Mysak

Reputation: 1252

Nestjs extend/combine decorators?

I have simple custom decorator:

export const User: () => ParameterDecorator = createParamDecorator(
  (data: any, req): UserIdentity => {
    const user = getUser(req);
    return user;
  },
); 

And now, I need to validate if we have email in user object.

The problem is that I can't update my current decorator.

Could I extend my current decorator?

Create a new decorator based on the previous one or create a new decorator and combine it?

Upvotes: 8

Views: 10836

Answers (1)

VinceOPS
VinceOPS

Reputation: 2720

Yes, you can do "decorator composition" with Nest, but this might not be a perfect solution for your case, depending on what you intend to do when user has no email property.

As per the example from the documentation:

import { applyDecorators } from '@nestjs/common';

export function Auth(...roles: Role[]) {
  return applyDecorators(
    SetMetadata('roles', roles),
    UseGuards(AuthGuard, RolesGuard),
    ApiBearerAuth(),
    ApiUnauthorizedResponse({ description: 'Unauthorized"' }),
  );
}

In this example, Auth is a decorator that can be used to combine all the one passed in applyDecorators.


Thus, I'd recommend extending your decorator using a pipe.

As stated by the documentation:

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 (in our examples, the user argument). Moreover, you can apply the pipe directly to the custom decorator:

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

In this example, User is a custom parameter decorator. And ValidationPipe is passed, but you can imagine passing any pipe.

Upvotes: 17

Related Questions