UNPKG

@inaiat/fastify-papr

Version:
74 lines (73 loc) 2.58 kB
// src/mongo-validation-error.ts import { MongoServerError } from "mongodb"; function isMongoServerError(error) { if (error instanceof 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; } }; export { isMongoServerError, extractValidationErrors, MongoValidationError }; //# sourceMappingURL=chunk-PUOOZXLB.js.map