|
| 1 | +const { defaultsDeep, lowerFirst, isObject, omit, isEmpty } = require('lodash'); |
| 2 | +const format = require('string-template'); |
| 3 | +const messages = require('./messages'); |
| 4 | +const { transformsError, errorx } = require('./utils'); |
| 5 | + |
| 6 | +function mongooseErrorHandler(error, options) { |
| 7 | + options = defaultsDeep(options, { |
| 8 | + capitalize: false, |
| 9 | + humanize: false, |
| 10 | + messages: messages, |
| 11 | + paths: {}, |
| 12 | + }); |
| 13 | + |
| 14 | + if (error.name === 'ValidationError') { |
| 15 | + const attr = Object.keys(error.errors).shift(); |
| 16 | + const err = error.errors[attr]; |
| 17 | + const { path, kind, value, properties, stringValue } = transformsError(err); |
| 18 | + const ex = errorx({ path, kind, value }); |
| 19 | + const agrs = { |
| 20 | + path, |
| 21 | + value: stringValue, |
| 22 | + ...properties, |
| 23 | + }; |
| 24 | + |
| 25 | + if (!isEmpty(options.paths) && options.paths[path]) { |
| 26 | + const po = options.paths[path]; |
| 27 | + if ( |
| 28 | + po.original === true && |
| 29 | + (isEmpty(po.kind) || (po.kind && po.kind === kind)) |
| 30 | + ) { |
| 31 | + return ex(err.message); |
| 32 | + } |
| 33 | + |
| 34 | + if (po.message && (isEmpty(po.kind) || (po.kind && po.kind === kind))) { |
| 35 | + return ex(format(po.message, agrs)); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + if (options.messages[kind]) { |
| 40 | + return ex(format(options.messages[kind], agrs)); |
| 41 | + } |
| 42 | + |
| 43 | + return ex(format(options.messages.base, agrs)); |
| 44 | + } |
| 45 | + |
| 46 | + return error; |
| 47 | +} |
| 48 | + |
| 49 | +module.exports = mongooseErrorHandler; |
0 commit comments