UNPKG

@inaiat/fastify-papr

Version:
54 lines (53 loc) 1.91 kB
import Papr from "papr"; //#region src/papr-helper.ts /** * Creates a helper for managing Papr models * Handles model registration and index creation * * @param fastify Fastify instance for logging * @param db MongoDB database connection * @param disableSchemaReconciliation Whether to skip schema validation reconciliation * @returns Object with registration methods */ const paprHelper = (fastify, db, disableSchemaReconciliation = false) => { const papr = new Papr(); papr.initialize(db); /** * Registers a model with Papr * @param collectionName MongoDB collection name * @param collectionSchema Schema definition and options * @returns Registered Papr model */ const registerModel = async (collectionName, collectionSchema) => { const model = papr.model(collectionName, collectionSchema); if (!disableSchemaReconciliation) await papr.updateSchema(model); return model; }; /** * Creates MongoDB indexes for a collection * @param collectionName MongoDB collection name * @param indexes Array of index descriptions * @returns Array of created index names */ const registerIndexes = async (collectionName, indexes) => db.collection(collectionName).createIndexes([...indexes]); return { /** * Registers multiple models at once * @param models Model registration definitions * @returns Object with registered models */ async register(models) { return Object.fromEntries(await Promise.all(Object.entries(models).map(async ([name, paprModel]) => { const model = await registerModel(paprModel.name, paprModel.schema); fastify.log.info(`Model ${name} decorated`); if (paprModel.indexes) { const index = await registerIndexes(paprModel.name, paprModel.indexes); fastify.log.info(`Indexes for ${paprModel.name} => ${index.join(", ")} created.`); } return [name, model]; }))); } }; }; //#endregion export { paprHelper }; //# sourceMappingURL=papr-helper.js.map