Parcourir la source

refactor: move ObjectID creation to DataModule using hooks

Co-authored-by: Owen Diffey <owen@diffey.dev>
Kristian Vos il y a 2 mois
Parent
commit
37ee36fd31

+ 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);
 	}
 }