-
Notifications
You must be signed in to change notification settings - Fork 38
/
index.js
246 lines (212 loc) · 7.48 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
'use strict';
var mongoose = require('mongoose');
var errorRegex = /index: (.+) dup key:/;
var indexesCache = {};
/**
* Check if the given error is a unique error.
*
* @param {Object} err Error to test.
* @return {bool} True if and only if it is an unique error.
*/
function isUniqueError(err) {
return err
&& (err.name === 'BulkWriteError' || err.name === 'MongoError')
&& (err.code === 11000 || err.code === 11001);
}
/**
* Search for the value matching a path in dotted notation
* inside an object.
*
* @example
* - getValueByPath({a: {b: 2}}, 'a.b') -> 2
* - getValueByPath({}, 'a.b') -> undefined
* @param {Object} obj Nested object to search.
* @param {string} path Path of the value to search for.
* @return {*} Matching value, or undefined if none.
*/
function getValueByPath(obj, path) {
var segments = path.split('.');
var result = obj;
for (
var i = 0;
i < segments.length
&& result !== null
&& result !== undefined;
++i
) {
result = result[segments[i]];
}
return result;
}
/**
* Recursively collect all messages inside a schema tree and
* change string values to `true`.
*
* @param {Object} tree Schema tree to update and collect from.
* @return {Object} Map of collected messages.
*/
function collectMessages(tree) {
var result = {};
for (var key in tree) {
if (tree.hasOwnProperty(key)) {
if (
typeof tree[key] === 'object'
&& tree[key] !== null
) {
if (typeof tree[key].unique === 'string') {
// Schema property that has a custom
// unique message
result[key] = tree[key].unique;
tree[key].unique = true;
} else {
// Nested schema
var subtree = collectMessages(tree[key]);
for (var subkey in subtree) {
if (subtree.hasOwnProperty(subkey)) {
result[key + '.' + subkey] = subtree[subkey];
}
}
}
}
}
}
return result;
}
/**
* Retrieve index information using collection#indexInformation
* or previously cached data.
*
* @param {Object} collection Mongoose collection.
* @return {Promise} Resolved with index information data.
*/
function getIndexes(collection) {
return new global.Promise(function (resolve, reject) {
if (indexesCache[collection.name]) {
resolve(indexesCache[collection.name]);
return;
}
collection.indexInformation(function (dbErr, indexes) {
if (dbErr) {
reject(dbErr);
return;
}
indexesCache[collection.name] = indexes;
resolve(indexes);
});
});
}
/**
* Beautify an E11000 or 11001 (unique constraint fail) Mongo error
* by turning it into a validation error
*
* @param {MongoError} err Error to process
* @param {Collection} collection Mongoose collection.
* @param {Object} values Hashmap containing data about duplicated values
* @param {Object} messages Map fields to unique error messages
* @param {String} defaultMessage Default message formatter string
* @return {Promise.<ValidationError>} Beautified error message
*/
function beautify(error, collection, values, messages, defaultMessage) {
// Try to recover the list of duplicated fields
var onSuberrors = global.Promise.resolve({});
// Extract the failed duplicate index's name from the
// from the error message (with a hacky regex)
var matches = errorRegex.exec(error.message);
if (matches) {
var indexName = matches[1];
// Retrieve that index's list of fields
onSuberrors = getIndexes(collection).then(function (indexes) {
var suberrors = {};
// Create a suberror per duplicated field
if (indexName in indexes) {
indexes[indexName].forEach(function (field) {
var path = field[0];
var props = {
type: 'unique',
path: path,
value: getValueByPath(values, path),
message: typeof messages[path] === 'string'
? messages[path] : defaultMessage
};
suberrors[path] = new mongoose.Error.ValidatorError(props);
});
}
return suberrors;
});
}
return onSuberrors.then(function (suberrors) {
var beautifiedError = new mongoose.Error.ValidationError();
beautifiedError.errors = suberrors;
return beautifiedError;
});
}
module.exports = function (schema, options) {
options = options || {};
if (!options.defaultMessage) {
options.defaultMessage = 'Path `{PATH}` ({VALUE}) is not unique.';
}
// Fetch error messages defined in the "unique" field,
// store them for later use and replace them with true
var tree = schema.tree;
var messages = collectMessages(tree);
schema._indexes.forEach(function (index) {
if (index[0] && index[1] && index[1].unique) {
Object.keys(index[0]).forEach(function (indexKey) {
messages[indexKey] = index[1].unique;
});
index[1].unique = true;
}
});
// Post hook that gets called after any save or update
// operation and that filters unique errors
var postHook = function (error, _, next) {
// Mongoose ≥5 does no longer pass the document as the
// second argument of 'update' hooks, so we use this instead
var doc = this;
// If the next() function is missing, this might be
// a sign that we are using an outdated Mongoose
if (typeof next !== 'function') {
throw new Error(
'mongoose-beautiful-unique-validation error: '
+ 'The hook was called incorrectly. Double check that '
+ 'you are using mongoose@>=4.5.0; if you need to use '
+ 'an outdated Mongoose version, please install this module '
+ 'in version 4.0.0'
);
}
if (isUniqueError(error)) {
// Beautify unicity constraint failure errors
var collection, values;
if (this.constructor.name == 'Query') {
collection = this.model.collection;
values = this._update;
if ('$set' in values) {
values = Object.assign({}, values, values.$set);
delete values.$set;
}
} else {
collection = doc.collection;
values = doc;
}
beautify(
error, collection, values,
messages, options.defaultMessage
)
.then(next)
.catch(function (beautifyError) {
setTimeout(function () {
throw new Error(
'mongoose-beautiful-unique-validation error: '
+ beautifyError.stack
);
});
});
} else {
// Pass over other errors
next(error);
}
};
schema.post('save', postHook);
schema.post('update', postHook);
schema.post('findOneAndUpdate', postHook);
};