【问题标题】:NestJS with TypeOrm: How do I save authentication information using @BeforeInsert and @BeforeUpdate?NestJS with TypeOrm:如何使用@BeforeInsert 和@BeforeUpdate 保存身份验证信息?
【发布时间】:2022-08-05 17:25:34
【问题描述】:

我有一个使用 TypeOrm 的 BaseEntity 的简单扩展,我想在执行 CRUD 操作时强制从请求中获取一些属性值。

import {
    Column,
    BaseEntity,
    PrimaryGeneratedColumn,
    BeforeInsert,
    BeforeUpdate
} from \"typeorm\";

import { IsOptional, IsNumber, IsDate, IsString } from \"class-validator\";

export class CrudEntity extends BaseEntity {
    @PrimaryGeneratedColumn()
    @IsOptional()
    @IsNumber()
    id?: number;

    @Column({ nullable: true, default: null })
    @IsString()
    @IsOptional()
    scope?: string;

    @Column({ nullable: true, default: null })
    @IsNumber()
    @IsOptional()
    client?: number;

    @Column({ nullable: true, default: null })
    @IsNumber()
    @IsOptional()
    user?: number;

    @Column({ type: \"timestamp\", default: () => \"CURRENT_TIMESTAMP\" })
    @IsDate()
    @IsOptional()
    created?: Date;

    @Column({ nullable: true, default: null })
    @IsNumber()
    @IsOptional()
    createdBy?: number;

    @Column({ type: \"timestamp\", nullable: true, default: null })
    @IsDate()
    @IsOptional()
    modified?: Date;

    @Column({ nullable: true, default: null })
    @IsNumber()
    @IsOptional()
    modifiedBy?: number;

    @BeforeInsert()
    public beforeInsert() {
        this.setClient();
        this.created = new Date();

        // @TODO Get info from JWT
        this.createdBy = null;
    }

    @BeforeUpdate()
    public beforeUpdate() {
        this.setClient();
        this.modified = new Date();

        // @TODO Get info from JWT
        this.modifiedBy = null;
    }

    public setClient() {
        // @TODO Get info from JWT
        this.scope = null;
        this.client = null;
    }
}

我需要一种方法来检索在请求标头中发送的解码的 JWT 令牌,以便保存谁在什么时间插入或更新了什么。

我已经阅读了有关请求范围、注入等的信息。我无法弄清楚或找到一个简单的解决方案来解决其他人在编写 NestJs 后端服务时肯定曾经遇到过的一个简单问题。

任何帮助是极大的赞赏。

  • 你试过订阅者吗? typeorm.io/#/listeners-and-subscribers/what-is-a-subscriber,另一个想法可能是您创建一个包含 TypeOrm 存储库的基本实体的基本存储库,以便您可以将当前用户作为依赖项注入到您的自定义基本存储库中,并在保存之前将其设置为基本实体。
  • 我肯定会看看我发现的所有方法都是过度设计的方法,如 cls-hooked、zone.js 和 request-context。
  • 最终在 CrudService 类中设置这些值并禁用级联。最初的问题是用户可以发布带有关系值的数据,而级联内的实体将无法正确设置。
  • 惊人的!您介意在此处添加您的解决方案吗?
  • 它更像是一种替代解决方案,因为我必须禁用级联,因此只有根记录从服务而不是关系更新。我说真正的解决方案是等待 NestJs 更改或 cls-hooked 的更简单替代方案,其余的用于获取请求上下文范围。

标签: mysql express jwt nestjs typeorm


【解决方案1】:

在我的例子中,@BeforeInsert@BeforeUpdate 没有被触发,因为我正在将 DTO 实例传递给我的服务。

如果您希望它们被触发,您必须使用 plainToClass(CrudEntity, dto) 将其转换为最终版本(此处为 CrudEntity)。当您的 DTO 包含与最终实体类不同的数据类型时,可能会很烦人

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 2012-03-06
    • 2015-10-28
    • 2021-05-31
    • 2012-03-23
    • 2021-02-12
    相关资源
    最近更新 更多