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

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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source