Good morning,
I'm trying to create a custom decorator:
user.decorator.ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
export const User = createParamDecorator(
(data: string, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
const user = request.user;
return data ? user && user[data] : user;
},
);
user.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, BeforeInsert } from "typeorm";
import * as bcrypt from 'bcryptjs';
import * as jwt from 'jsonwebtoken';
import { UserRO } from "./user.dto";
@Entity("user")
export class UserEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({
type: 'varchar',
length: 50,
unique: true,
})
username: string;
@Column('text')
password: string;
@Column('text')
role: string;
(...)
}
And finally, user.controller.ts (only the useful part):
(...)
@Post('login')
@UsePipes(new ValidationPipe())
login(@Body() data: UserDTO, @User('role') role: string) {
console.log(`hello ${role}`);
return this.userService.login(data);
(...)
}
My problem: console.log(...) returns me hello undefined, when the expected response should be hello admin (as admin is the role of the user in the database)
EDIT: I also tried to console.log(user) in my decorator and it is undefined too.
EDIT2: My HttpErrorFilter also says: Cannot read property 'role' of undefined
I followed closely the documentation and I can't figure out where the problem is (https://docs.nestjs.com/custom-decorators).
Thank you for your time.