NestJS with TypeOrm: How do I save authentication information using @BeforeInsert and @BeforeUpdate?

Viewed 958

I have a simple extension of BaseEntity using TypeOrm for which I want to force some property values obtained from the request when doing CRUD operations.

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;
    }
}

I need a way to retrieve the decoded JWT token sent in the request headers in order to save who insert or updated what at what time.

I have read about request scopes, injection, etc. I haven't been able to figure it out or find a simple solution to a simple problem someone else must have certainly faced at one point while writing a NestJs backend service.

Any help is greatly appreciated.

1 Answers

In my case, @BeforeInsert and @BeforeUpdate was not triggered because I was passing DTO instances to my service.

If you want them to be triggered, you must convert it in their final (here its CrudEntity) using plainToClass(CrudEntity, dto) for instance. Can be quite annoying when your DTO includes data types that differs from your final entity class

Related