import { Investigation } from "@models/investigation/investigation.model";
import { getLogger } from "@utils/asyncLocalStorage";
import { Types } from "mongoose";
/**
* Ensures that the author of a given investigation is set.
*
* If the investigation exists and does not already have a valid author, this method sets the author
* to the provided `authorId` and updates the `dateModified` field.
* @category Services
* @param {string} investigationId - The ID of the investigation to check.
* @param {Types.ObjectId} authorId - The ObjectId of the author to set.
* @returns {Promise<IInvestigation | null>} - The updated investigation object, or `null` if the investigation does not exist or already has a valid author.
* @throws {Error} If there is an error during the process of fetching or saving the investigation.
*/
export async function ensureInvestigationAuthor(investigationId, authorId) {
const logger = getLogger();
try {
const investigation = await Investigation.findById(investigationId);
if (!investigation) {
return null;
}
const currentAuthor = investigation.metadata?.author;
if (currentAuthor && Types.ObjectId.isValid(currentAuthor.toString())) {
return null;
}
if (!investigation.metadata) {
investigation.metadata = {};
}
investigation.metadata.author = authorId;
investigation.metadata.dateModified = new Date();
const saved = await investigation.save();
return saved.toObject();
}
catch (error) {
logger.error({ error, investigationId, authorId }, "Failed to ensure investigation author");
throw new Error("Failed to ensure investigation author");
}
}
Source