Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS createParamDecorator return undefined

I'm using Nest version ^6.7.2

I'm trying to create a createParamDecorator that gets the req.user value from a request.

Inside the createParamDecorator, the req.user has a value, however when I try to get the value in a controller by using the decorator the value is undefined.

const AuthSession = createParamDecorator((data, req) => {
  console.log(req.user); // session data
  return req.user;
});
Controller()
export default class AuthController {
  @Get("/token/ping")
  @UseGuards(AuthGuard("jwt"))
  tokenPing(@AuthSession() session: Session) {
    console.log(session); // undefined
    return session;
  }
}

Edit: I just tried updating to nestjs v7 and I'm having the same issue

import { createParamDecorator, ExecutionContext } from "@nestjs/common";

const AuthSession = createParamDecorator((data: any, ctx: ExecutionContext) => {
  return { message: "asdf" };
});

export default AuthSession;
@Controller()
export default class AuthController {
  @Get("/token/ping")
  @UseGuards(AuthGuard("jwt"))
  tokenPing(@AuthSession() session: Session) {
    console.log(session); // undefined
    return session;
  }
}
like image 930
user1991252 Avatar asked Jan 24 '23 14:01

user1991252


1 Answers

you can get the information firs from ExecutionContext:

    import { createParamDecorator, ExecutionContext } from '@nestjs/common';

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

check the example in the doc : Custom decorator

like image 86
Youba Avatar answered Feb 04 '23 09:02

Youba