I'm using nestjs and I was trying to create a custom decorator:
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { User } from './user.entity';
export const GetUser = createParamDecorator(
(data, ctx: ExecutionContext): User => {
const req = ctx.switchToHttp().getRequest();
return req.user;
},
);
The decorator is used here:
@Post('/test')
@UseGuards(AuthGuard())
test(@GetUser() user: User) {
console.log(user);
}
But I get the following error:
[Nest] 15053 - 26/03/2020, 13:28:19 [ExceptionsHandler] ctx.switchToHttp is not a function +61625ms
TypeError: ctx.switchToHttp is not a function
at /Users/nelson.larios/Documents/nestjs/nestjs-task-management/dist/auth/get-user.decorator.js:5:21
at /Users/nelson.larios/Documents/nestjs/nestjs-task-management/node_modules/@nestjs/core/router/router-execution-context.js:115:35
at resolveParamValue (/Users/nelson.larios/Documents/nestjs/nestjs-task-management/node_modules/@nestjs/core/router/router-execution-context.js:143:31)
at Array.map (<anonymous>)
at pipesFn (/Users/nelson.larios/Documents/nestjs/nestjs-task-management/node_modules/@nestjs/core/router/router-execution-context.js:148:45)
at /Users/nelson.larios/Documents/nestjs/nestjs-task-management/node_modules/@nestjs/core/router/router-execution-context.js:36:36
at InterceptorsConsumer.intercept (/Users/nelson.larios/Documents/nestjs/nestjs-task-management/node_modules/@nestjs/core/interceptors/interceptors-consumer.js:10:20)
at /Users/nelson.larios/Documents/nestjs/nestjs-task-management/node_modules/@nestjs/core/router/router-execution-context.js:45:60
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async /Users/nelson.larios/Documents/nestjs/nestjs-task-management/node_modules/@nestjs/core/router/router-proxy.js:8:17
Any thoughts?
Thanks
Prior to version 7.x, Custom Decorators were static, and thus did not get the ExecutionContext
passed to them. In v7.x release, this has been added.
As mentioned in comments on the OP's question, you need to upgrade to this version to get the example in the documentation working.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With