UNPKG

@inaiat/fastify-papr

Version:
199 lines (194 loc) 7.12 kB
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { MongoValidationError: () => MongoValidationError, asCollection: () => asCollection, default: () => fastifyPaprPlugin, extractValidationErrors: () => extractValidationErrors, fastifyPaprPlugin: () => fastifyPaprPlugin, isMongoServerError: () => isMongoServerError }); module.exports = __toCommonJS(index_exports); // src/fastify-papr-plugin.ts var import_fastify_plugin = __toESM(require("fastify-plugin"), 1); // src/papr-helper.ts var import_papr = __toESM(require("papr"), 1); var paprHelper = (fastify, db, disableSchemaReconciliation = false) => { const papr = new import_papr.default(); papr.initialize(db); const registerModel = async (collectionName, collectionSchema) => { const model = papr.model(collectionName, collectionSchema); if (!disableSchemaReconciliation) { await papr.updateSchema(model); } return model; }; 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]; }) ) ); } }; }; // src/fastify-papr-plugin.ts var asCollection = (name, schema, indexes) => ({ name, schema, indexes }); var fastifyPaprPlugin = async (mutable_fastify, options) => { const helper = paprHelper( mutable_fastify, options.db, options.disableSchemaReconciliation ); const models = await helper.register(options.models); const { name: dbName } = options; if (dbName) { if (mutable_fastify.papr) { if (mutable_fastify.papr[dbName]) { throw new Error(`Connection name already registered: ${dbName}`); } mutable_fastify.log.info(`Registering connection name: ${dbName}`); mutable_fastify.papr = { ...mutable_fastify.papr, [dbName]: models }; } else { mutable_fastify.decorate("papr", { [dbName]: models }); } } else { if (mutable_fastify.papr) { const items = Object.keys(mutable_fastify.papr).join(", "); throw new Error(`Models already registered: ${items}`); } else { mutable_fastify.decorate("papr", models); } } }; var fastify_papr_plugin_default = (0, import_fastify_plugin.default)(fastifyPaprPlugin, { name: "fastify-papr-plugin", fastify: "4.x || 5.x" }); // src/mongo-validation-error.ts var import_mongodb = require("mongodb"); function isMongoServerError(error) { if (error instanceof import_mongodb.MongoServerError) { return true; } const errorWithCode = error; return error instanceof Error && typeof errorWithCode.code === "number"; } var formatValidationProperties = (properties) => properties?.map((prop) => ({ [prop.propertyName]: prop.details })); function extractValidationErrors(error) { if (!isMongoServerError(error) || error.code !== 121) { return void 0; } const errInfo = error.errInfo; if (!errInfo?.details?.schemaRulesNotSatisfied?.length) { return void 0; } const schemaRulesNotSatisfied = errInfo.details.schemaRulesNotSatisfied; const result = schemaRulesNotSatisfied.map((rule) => ({ [rule.operatorName]: formatValidationProperties(rule.propertiesNotSatisfied || []) })); return result.length > 0 ? result : void 0; } var MongoValidationError = class extends Error { /** The extracted validation rules that weren't satisfied */ validationErrors; /** Flag indicating whether this is a document validation error */ hasValidationFailures; /** * Creates an instance from a MongoDB server error * @param mongoError The original MongoDB error */ constructor(mongoError) { super(mongoError.message, { cause: mongoError }); this.validationErrors = extractValidationErrors(mongoError); this.hasValidationFailures = this.validationErrors !== void 0; } /** * Returns the validation errors as a JSON string * @returns A JSON string of the validation errors or undefined if not a validation error */ getValidationErrorsAsString() { return this.hasValidationFailures ? JSON.stringify(this.validationErrors) : void 0; } /** * Finds validation errors for a specific field * @param fieldName The field name to find errors for * @returns Array of validation details for the field or undefined if none found */ getFieldErrors(fieldName) { if (!this.hasValidationFailures || !this.validationErrors?.length) { return void 0; } for (const ruleSet of this.validationErrors) { for (const [, properties] of Object.entries(ruleSet)) { for (const property of properties) { const field = Object.keys(property).find((key) => key === fieldName); if (field) { return property[field]; } } } } return void 0; } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { MongoValidationError, asCollection, extractValidationErrors, fastifyPaprPlugin, isMongoServerError }); //# sourceMappingURL=index.cjs.map