UNPKG

express-api-problem

Version:

A minimal package to assist in returning RESTful exceptions in your APIs

28 lines (27 loc) 1.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const http_status_codes_1 = require("http-status-codes"); const api_problem_1 = require("./api-problem"); function getMongooseErrorHandler(options = {}) { function validationErrorHandler(err, doc, next) { if (err.name !== 'ValidationError') { return next(err); } const typedError = err; const formattedErrors = []; // For each of the mongo errors, format them for (const error in typedError.errors) { formattedErrors.push({ field: typedError.errors[error].path, message: typedError.errors[error].message, }); } next(new api_problem_1.ApiProblem(Object.assign(Object.assign({ status: options.status || http_status_codes_1.UNPROCESSABLE_ENTITY, title: options.title || 'Validation Failed' }, options), { detail: formattedErrors }))); } return validationErrorHandler; } exports.getMongooseErrorHandler = getMongooseErrorHandler; function MongooseProblemPlugin(schema, options = {}) { schema.post('save', getMongooseErrorHandler(options)); } exports.MongooseProblemPlugin = MongooseProblemPlugin;