|
|
@@ -3,12 +3,17 @@ import { z } from '@hono/zod-openapi';
|
|
|
|
|
|
export abstract class GenericCrudService<T extends ObjectLiteral> {
|
|
|
protected repository: Repository<T>;
|
|
|
+ private userTrackingOptions?: UserTrackingOptions;
|
|
|
|
|
|
constructor(
|
|
|
protected dataSource: DataSource,
|
|
|
- protected entity: new () => T
|
|
|
+ protected entity: new () => T,
|
|
|
+ options?: {
|
|
|
+ userTracking?: UserTrackingOptions;
|
|
|
+ }
|
|
|
) {
|
|
|
this.repository = this.dataSource.getRepository(entity);
|
|
|
+ this.userTrackingOptions = options?.userTracking;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -120,19 +125,42 @@ export abstract class GenericCrudService<T extends ObjectLiteral> {
|
|
|
});
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * 设置用户跟踪字段
|
|
|
+ */
|
|
|
+ private setUserFields(data: any, userId?: string | number, isCreate: boolean = true): void {
|
|
|
+ if (!this.userTrackingOptions || !userId) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ const { createdByField = 'createdBy', updatedByField = 'updatedBy' } = this.userTrackingOptions;
|
|
|
+
|
|
|
+ if (isCreate && createdByField) {
|
|
|
+ data[createdByField] = userId;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (updatedByField) {
|
|
|
+ data[updatedByField] = userId;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 创建实体
|
|
|
*/
|
|
|
- async create(data: DeepPartial<T>): Promise<T> {
|
|
|
- const entity = this.repository.create(data as DeepPartial<T>);
|
|
|
+ async create(data: DeepPartial<T>, userId?: string | number): Promise<T> {
|
|
|
+ const entityData = { ...data };
|
|
|
+ this.setUserFields(entityData, userId, true);
|
|
|
+ const entity = this.repository.create(entityData as DeepPartial<T>);
|
|
|
return this.repository.save(entity);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 更新实体
|
|
|
*/
|
|
|
- async update(id: number, data: Partial<T>): Promise<T | null> {
|
|
|
- await this.repository.update(id, data);
|
|
|
+ async update(id: number, data: Partial<T>, userId?: string | number): Promise<T | null> {
|
|
|
+ const updateData = { ...data };
|
|
|
+ this.setUserFields(updateData, userId, false);
|
|
|
+ await this.repository.update(id, updateData);
|
|
|
return this.getById(id);
|
|
|
}
|
|
|
|
|
|
@@ -152,6 +180,11 @@ export abstract class GenericCrudService<T extends ObjectLiteral> {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+export interface UserTrackingOptions {
|
|
|
+ createdByField?: string;
|
|
|
+ updatedByField?: string;
|
|
|
+}
|
|
|
+
|
|
|
export type CrudOptions<
|
|
|
T extends ObjectLiteral,
|
|
|
CreateSchema extends z.ZodSchema = z.ZodSchema,
|
|
|
@@ -167,4 +200,5 @@ export type CrudOptions<
|
|
|
searchFields?: string[];
|
|
|
relations?: string[];
|
|
|
middleware?: any[];
|
|
|
+ userTracking?: UserTrackingOptions;
|
|
|
};
|