Currently tackling a project in nestJs that requires adding audit columns to certain entities. I have set up user information on a request object, which seems to be working fine when printed in the controller. However, I am facing issues with implementing this in entity classes.
My attempted approach is as follows:
import { Req } from "@nestjs/common";
import { Exclude } from "class-transformer";
import { BeforeInsert, BeforeUpdate, Column, CreateDateColumn, DeleteDateColumn, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
export class BaseModel{
@PrimaryGeneratedColumn('uuid')
id:string
@CreateDateColumn()
created_at:Date
@Column({default:null})
created_by:string
@UpdateDateColumn()
modified_at:Date
@Column({default:null})
modified_by:string
@DeleteDateColumn({select:false})
@Exclude()
deleted_at:Date
@BeforeInsert()
setAuditsBeforeInsert(@Req() req:any){
this.created_by=req.currentUser.id;
this.modified_by=req.currentUser.id;
}
@BeforeUpdate()
setAuditsBeforeUpdate(@Req() req:any){
this.modified_by=req.currentUser.id;
}
}
Problem arises in @BeforeInsert() and @BeforeUpdate() hooks where the request object is undefined. Any assistance would be greatly appreciated. Alternatively, please suggest a correct method for setting createdBy and modifiedBy columns with userId.