Parcourir la source

feat: add FindManyById job

Kristian Vos il y a 1 an
Parent
commit
5192b28c45

+ 27 - 0
backend/src/modules/DataModule/FindManyByIdJob.ts

@@ -0,0 +1,27 @@
+import { isValidObjectId } from "mongoose";
+import DataModule from "../DataModule";
+import DataModuleJob from "./DataModuleJob";
+
+export default abstract class FindManyByIdJob extends DataModuleJob {
+	protected override async _validate() {
+		if (typeof this._payload !== "object" || this._payload === null)
+			throw new Error("Payload must be an object");
+		if (!Array.isArray(this._payload._ids))
+			throw new Error("Payload._ids must be an array");
+		if (!this._payload._ids.every((_id: unknown) => isValidObjectId(_id)))
+			throw new Error(
+				"One or more payload._ids item(s) is not a valid ObjectId"
+			);
+	}
+
+	protected async _execute() {
+		const model = await DataModule.getModel(this.getModelName());
+
+		const _ids = this._payload._ids;
+		const query = model.find({
+			_id: _ids
+		});
+
+		return query.exec();
+	}
+}

+ 9 - 0
backend/src/modules/DataModule/models/minifiedUsers/jobs/FindManyById.ts

@@ -0,0 +1,9 @@
+import FindManyByIdJob from "@/modules/DataModule/FindManyByIdJob";
+
+export default class FindManyById extends FindManyByIdJob {
+	protected static _modelName = "minifiedUsers";
+
+	protected static _hasPermission = true;
+
+	protected async _authorize() {}
+}

+ 21 - 0
frontend/src/stores/model.ts

@@ -222,6 +222,26 @@ export const useModelStore = defineStore("model", () => {
 		return runJob(`data.${modelName}.findById`, { _id });
 	};
 
+	const findManyById = async (modelName: string, _ids: string[]) => {
+		const existingModels = models.value.filter(model =>
+			_ids.includes(model._id)
+		);
+		const existingIds = existingModels.map(model => model._id);
+		const missingIds = _ids.filter(_id => !existingIds.includes(_id));
+
+		let fetchedModels = [];
+		if (missingIds.length > 0)
+			fetchedModels = (await runJob(`data.${modelName}.findManyById`, {
+				_ids: missingIds
+			})) as unknown[];
+
+		const allModels = existingModels.concat(fetchedModels);
+
+		return Object.fromEntries(
+			_ids.map(_id => [_id, allModels.find(model => model._id === _id)])
+		);
+	};
+
 	const loadModels = async (
 		modelName: string,
 		modelIds: string | string[],
@@ -257,6 +277,7 @@ export const useModelStore = defineStore("model", () => {
 		getUserModelPermissions,
 		hasPermission,
 		findById,
+		findManyById,
 		loadModels
 	};
 });