Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ctx.switchToHttp is not a function

Tags:

nestjs

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

like image 295
Nelson Larios Avatar asked Mar 02 '23 15:03

Nelson Larios


1 Answers

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.

like image 62
Zach Gollwitzer Avatar answered Apr 12 '23 15:04

Zach Gollwitzer