Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom GetUser Decorator #8

Open
dyaliCode opened this issue Apr 27, 2020 · 2 comments
Open

Custom GetUser Decorator #8

dyaliCode opened this issue Apr 27, 2020 · 2 comments

Comments

@dyaliCode
Copy link

dyaliCode commented Apr 27, 2020

I guess with last version of nestjs, couldn't get req.user
because you will recive undefined data

make sure and test with last version !

Controller :

@Post('/test')
  @UseGuards(AuthGuard())
  test(@GetUser() user) {
    console.log('user', user);
  }

Decorator:

export const GetUser = createParamDecorator(
  (data, req): User => {
    return req.user;
  },
);

Console Output:
user undefined

So change code custom decorator to :

export const GetUser = createParamDecorator(
  (data, ctx: ExecutionContext): User => {
    const req = ctx.switchToHttp().getRequest();
    return req.user;
  },
);
@null-char
Copy link

Yeah. This one had me confused for a bit. I guess it's wise to always check the docs for the latest information. Apparently, NestJS changed the syntax for createParamDecorator a while ago.

@benyou1969
Copy link

I had the same issue until I added ExecutionContext.

try this code

import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { User } from './user.entity';

export const GetUser = createParamDecorator(
  (data: unknown, ctx: ExecutionContext): User => {
    const request = ctx.switchToHttp().getRequest();
    return request.user;
  },
);

more info visit nestjs documentation for creating new Custom Decorator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants