const { ObjectId } = require("mongodb"); let ensureIndexesPromise = null; async function ensureApplicableDiagnosisIndexes(db) { if (!ensureIndexesPromise) { ensureIndexesPromise = Promise.all([ db.collection("drug-info").createIndex({ applicableDiagnosisIds: 1 }), db.collection("online-drug-info").createIndex({ applicableDiagnosisIds: 1 }), ]).catch((error) => { ensureIndexesPromise = null; throw error; }); } await ensureIndexesPromise; } async function validateApplicableDiagnosisIds(params, db) { if (!Object.prototype.hasOwnProperty.call(params, "applicableDiagnosisIds")) { return { present: false, value: [] }; } const rawIds = params.applicableDiagnosisIds; if (!Array.isArray(rawIds)) { throw new Error("适应诊断格式错误"); } const uniqueIds = []; const seen = new Set(); for (const rawId of rawIds) { if (typeof rawId !== "string" || !ObjectId.isValid(rawId.trim())) { throw new Error("适应诊断包含无效ID"); } const id = rawId.trim(); if (!seen.has(id)) { seen.add(id); uniqueIds.push(new ObjectId(id)); } } if (uniqueIds.length) { const diagnosisCount = await db.collection("hlw-diagnosis").countDocuments({ _id: { $in: uniqueIds }, }); if (diagnosisCount !== uniqueIds.length) { throw new Error("部分适应诊断不存在,请重新选择"); } } await ensureApplicableDiagnosisIndexes(db); return { present: true, value: uniqueIds }; } module.exports = { ensureApplicableDiagnosisIndexes, validateApplicableDiagnosisIds, };