浏览代码

refactor: move ObjectID creation to DataModule using hooks

Co-authored-by: Owen Diffey <owen@diffey.dev>
Kristian Vos 2 月之前
父节点
当前提交
37ee36fd31
共有 2 个文件被更改,包括 7 次插入3 次删除
  1. 7 0
      backend/src/modules/DataModule.ts
  2. 0 3
      backend/src/modules/DataModule/CreateJob.ts

+ 7 - 0
backend/src/modules/DataModule.ts

@@ -266,6 +266,13 @@ export class DataModule extends BaseModule {
 						model.previous("_id")
 					)
 				);
+			},
+			beforeValidate: async model => {
+				if (model.isNewRecord) {
+					const key = (model.constructor as ModelStatic<any>)
+						.primaryKeyAttribute;
+					model.dataValues[key] ??= ObjectID();
+				}
 			}
 		};
 	}

+ 0 - 3
backend/src/modules/DataModule/CreateJob.ts

@@ -1,5 +1,4 @@
 import Joi from "joi";
-import ObjectID from "bson-objectid";
 import DataModuleJob from "./DataModuleJob";
 
 export default abstract class CreateJob extends DataModuleJob {
@@ -15,8 +14,6 @@ export default abstract class CreateJob extends DataModuleJob {
 		if (Object.hasOwn(model.getAttributes(), "createdBy"))
 			query.createdBy = (await this._context.getUser())._id;
 
-		query[model.primaryKeyAttribute] = ObjectID();
-
 		return model.create(query);
 	}
 }