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

2023-12-21

早上好,

我正在尝试创建一个自定义装饰器: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;

    (...)
}

最后,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);
(...)
    }

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

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

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

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

感谢您的时间。


我也曾对此感到困惑。我升级到 NestJS 7,并遵循迁移指南 https://docs.nestjs.com/migration-guide试图更新我的用户装饰器。

我无法工作的部分是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;
  }
);

The 执行上下文 https://docs.nestjs.com/fundamentals/execution-context文档建议不要getArgByIndex(),所以我确信我做了一些简单的错误。对其他答案和评论会说些什么感兴趣。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NestJS 自定义装饰器返回未定义 的相关文章

随机推荐