NestJS 自定义装饰器返回未定义

MA-*_*che 3 typescript typeorm nestjs

早上好,

我正在尝试创建一个自定义装饰器: 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;
  },
);
Run Code Online (Sandbox Code Playgroud)

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;

    (...)
}

Run Code Online (Sandbox Code Playgroud)

最后,user.controller.ts(仅有用的部分):

(...)
    @Post('login')
    @UsePipes(new ValidationPipe())
    login(@Body() data: UserDTO,  @User('role') role: string) {
        console.log(`hello ${role}`);
        return this.userService.login(data);
(...)
    }
Run Code Online (Sandbox Code Playgroud)

我的问题: console.log(...) 返回 me hello undefined,而预期的响应应该是hello admin(因为 admin 是数据库中用户的角色)

编辑:我也尝试console.log(user)在我的装饰器中,它也未定义。

EDIT2:我的 HttpErrorFilter 还说:Cannot read property 'role' of undefined

我密切关注文档,但无法弄清楚问题出在哪里(https://docs.nestjs.com/custom-decorators)。

感谢您的时间。

Der*_*ill 5

我也曾对此感到困惑。我升级到 NestJS 7,并按照迁移指南尝试更新我的用户装饰器。

我无法工作的部分是const request = ctx.switchToHttp().getRequest();。由于某种原因getRequest()返回未定义。

对我有用的是:

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

export const CurrentUser = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    return ctx.getArgByIndex(2).req.user;
  }
);
Run Code Online (Sandbox Code Playgroud)

执行上下文文档建议不要这样做getArgByIndex(),所以我确信我正在做一些简单的错误。对其他答案和评论会说些什么感兴趣。