Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get user data with req.user on decorator in nest js

I created the authentication ( jwt ) and the process is done properly.

I can access the user's information using the following code, but I can't get the user's information using the decorator!

controller :

@Post('/me/info')
  @UseGuards(AuthGuard())
  myInfo(
    @GetUser() user,
    @Req() req,
  ) {
    console.log(user); // undefined 
    console.log(req.user); // get user data object
  }

my decorator is:

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

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

what is my code problem ?

like image 961
moh Avatar asked Jun 10 '20 09:06

moh


1 Answers

The problem is in createParamDecorator.

An excerpt from the official manual on custom decorators:

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

export const User = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return request.user;
  },
);
like image 147
Naor Levi Avatar answered Sep 19 '22 21:09

Naor Levi