NestJS 自定义装饰器返回未定义 [英] NestJS custom decorator returns undefined

查看:52
本文介绍了NestJS 自定义装饰器返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好,

我正在尝试创建一个自定义装饰器:user.decorator.ts

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;

    (...)
}

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

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

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

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)

我也尝试在我的装饰器中 console.log(user) 并且它也未定义.

I also tried to console.log(user) in my decorator and it is undefined too.

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

My HttpErrorFilter also says: Cannot read property 'role' of undefined

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

I followed closely the documentation and I can't figure out where the problem is (https://docs.nestjs.com/custom-decorators).

感谢您抽出宝贵时间.

推荐答案

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

I have also been confused about this. I upgraded to NestJS 7, and following the migration guide was trying to update my user decorator.

我无法工作的部分是const request = ctx.switchToHttp().getRequest();.出于某种原因,getRequest() 返回了 undefined.

The part I could not get working is const request = ctx.switchToHttp().getRequest();. For some reason getRequest() was returning undefined.

对我有用的是:

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

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

执行上下文 文档建议不要使用 getArgByIndex(),所以我确定我做错了一些简单的事情.对其他答案和评论的内容感兴趣.

The execution context docs advise against getArgByIndex(), so I'm sure I'm doing something simple wrong. Interested in what the other answers and comments will say.

这篇关于NestJS 自定义装饰器返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆