express-api-problem
Version:
A minimal package to assist in returning RESTful exceptions in your APIs
28 lines (27 loc) • 1.17 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const http_status_codes_1 = require("http-status-codes");
const api_problem_1 = require("./api-problem");
function getErrorHandler(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.getErrorHandler = getErrorHandler;
function MongoosePlugin(schema, options = {}) {
schema.post('save', getErrorHandler(options));
}
exports.MongoosePlugin = MongoosePlugin;