返回
Nestjs 中的操作日志:追溯用户数据操作的最佳实践
前端
2024-01-06 10:27:44
前言
在现代软件系统中,记录用户对数据的操作至关重要。操作日志可以帮助我们跟踪数据变更的历史记录,便于故障排查、审计和安全分析。在 Nestjs 中,我们可以使用 TypeORM 的 subscriber 来监听数据库的变动,并使用 Nestjs 的模块化设计和依赖注入来构建一个灵活易用的日志记录系统。
实现步骤
1. 安装依赖
首先,我们需要安装 TypeORM 和 Nestjs 的相关依赖。
npm install --save typeorm nestjs-typeorm
2. 创建实体
接下来,我们需要创建一个实体类来表示我们要记录的操作日志。
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class OperationLog {
@PrimaryGeneratedColumn()
id: number;
@Column()
userId: number;
@Column()
tableName: string;
@Column()
operation: string;
@Column()
oldValue: string;
@Column()
newValue: string;
@Column()
createdAt: Date;
}
3. 创建 subscriber
接下来,我们需要创建一个 subscriber 来监听数据库的变动。
import { EntitySubscriberInterface, EventSubscriber, InsertEvent, UpdateEvent, DeleteEvent } from 'typeorm';
import { OperationLog } from './operation-log.entity';
@EventSubscriber()
export class OperationLogSubscriber implements EntitySubscriberInterface<OperationLog> {
listenTo() {
return OperationLog;
}
beforeInsert(event: InsertEvent<OperationLog>) {
console.log(`New operation log: ${event.entity.userId} ${event.entity.tableName} ${event.entity.operation}`);
}
beforeUpdate(event: UpdateEvent<OperationLog>) {
console.log(`Updated operation log: ${event.entity.userId} ${event.entity.tableName} ${event.entity.operation}`);
}
beforeDelete(event: DeleteEvent<OperationLog>) {
console.log(`Deleted operation log: ${event.entity.userId} ${event.entity.tableName} ${event.entity.operation}`);
}
}
4. 注册 subscriber
最后,我们需要在 Nestjs 模块中注册 subscriber。
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { OperationLog } from './operation-log.entity';
import { OperationLogSubscriber } from './operation-log.subscriber';
@Module({
imports: [
TypeOrmModule.forFeature([OperationLog]),
],
providers: [
OperationLogSubscriber,
],
})
export class OperationLogModule {}
使用
现在,我们可以在 Nestjs 服务中使用 OperationLogService 来记录操作日志。
import { Injectable } from '@nestjs/common';
import { OperationLogService } from './operation-log.service';
@Injectable()
export class AppService {
constructor(private readonly operationLogService: OperationLogService) {}
async logOperation(userId: number, tableName: string, operation: string, oldValue: string, newValue: string) {
await this.operationLogService.logOperation(userId, tableName, operation, oldValue, newValue);
}
}
结语
以上就是如何在 Nestjs 中实现操作日志的完整步骤。希望这篇文章对您有所帮助。如果您有任何问题,请随时留言。

扫码关注微信公众号
WebGPU 中的纹理: 全面指南

{ text-align: center; font-size: 24px; font-weight: bold; padding: 12px; } #keywords { text-align: center; font-size: 14px; padding: 12px; } #description { text-align: center; font-size: 16px; padding: 12px; } </style> Vue中的侦听器:watch vs. watchEffect
深入理解 MsgPack:从一个 JSF 上线问题说起
WebCodecs赋能:网页端高性能视频截帧技术探索
