forked from rusty1s/mongoose-i18n-error
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (78 loc) · 2.17 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* jshint node: true */
'use strict';
module.exports = function(options) {
this.prefix = (options || {}).prefix || 'error.';
this.handler = function(handler) {
var self = this;
return function(err, req, res, next) {
if (!err) return next(err);
if (typeof res.__ !== 'function') {
console.error('no i18n.__ function found.');
return next(err);
}
var i18nErr = self.parseValidationError(err, res.__) || self.parseUniqueError(err, res.__);
if (i18nErr) return handler(i18nErr, req, res, next);
else return next(err);
};
};
this.parseValidationError = function(err, __) {
if (!err) return null;
if (err.name !== 'ValidationError') return null;
var result = {};
for (var key in err.errors) {
var error = err.errors[key];
var type = error.kind;
var condition;
var message = this.prefix;
// cast error
if (error.name === 'CastError') {
type = 'cast';
message += type;
}
// match or enum error
else if (type === 'regexp' || type === 'enum') {
var model = /(.*)\svalidation\sfailed/.exec(err.message)[1].toLowerCase();
message += model + '.' + key + '.' + type;
}
// custom validation error
else if (type.match(/user defined/)) {
type = error.message.split(/\./g).reverse()[0];
message += error.message;
}
// all other errors
else {
if (error.properties) condition = error.properties[type];
message += type;
}
result[key] = {
type: type,
message: __(message, condition),
value: error.value
};
}
return result;
};
this.parseUniqueError = function(err, __) {
if (!err) return null;
if (err.name !== 'MongoError') return null;
if (err.code !== 11000 && err.code !== 11001) return null;
var matches = /index:\s(.*)(?:_\d?)\sdup key:\s\{\s:\s"(.*)"\s\}/.exec(err.message);
if (!matches || matches.length != 3){
matches = /index:\s(.*)(?:_\d?)\sdup key:\s\{\s:\s(.*)\s\}/.exec(err.message);
if (!matches || matches.length != 3){
matches = [
'',
'unknown',
'unknown',
];
}
}
var result = {};
result[matches[1]] = {
type: 'unique',
message: __(this.prefix + 'unique'),
value: matches[2]
};
return result;
};
};