-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathindex.js
321 lines (267 loc) · 10.9 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
Model = mongoose.Model,
util = require('util');
/**
* This code is taken from official mongoose repository
* https://github.com/Automattic/mongoose/blob/master/lib/query.js#L3847-L3873
*/
function parseUpdateArguments (conditions, doc, options, callback) {
if ('function' === typeof options) {
// .update(conditions, doc, callback)
callback = options;
options = null;
} else if ('function' === typeof doc) {
// .update(doc, callback);
callback = doc;
doc = conditions;
conditions = {};
options = null;
} else if ('function' === typeof conditions) {
// .update(callback)
callback = conditions;
conditions = undefined;
doc = undefined;
options = undefined;
} else if (typeof conditions === 'object' && !doc && !options && !callback) {
// .update(doc)
doc = conditions;
conditions = undefined;
options = undefined;
callback = undefined;
}
var args = [];
if (conditions) args.push(conditions);
if (doc) args.push(doc);
if (options) args.push(options);
if (callback) args.push(callback);
return args;
}
function parseIndexFields (options) {
var indexFields = {
deleted: false,
deletedAt: false,
deletedBy: false
};
if (!options.indexFields) {
return indexFields;
}
if ((typeof options.indexFields === 'string' || options.indexFields instanceof String) && options.indexFields === 'all') {
indexFields.deleted = indexFields.deletedAt = indexFields.deletedBy = true;
}
if (typeof(options.indexFields) === "boolean" && options.indexFields === true) {
indexFields.deleted = indexFields.deletedAt = indexFields.deletedBy = true;
}
if (Array.isArray(options.indexFields)) {
indexFields.deleted = options.indexFields.indexOf('deleted') > -1;
indexFields.deletedAt = options.indexFields.indexOf('deletedAt') > -1;
indexFields.deletedBy = options.indexFields.indexOf('deletedBy') > -1;
}
return indexFields;
}
function createSchemaObject (typeKey, typeValue, options) {
options[typeKey] = typeValue;
return options;
}
module.exports = function (schema, options) {
options = options || {};
var indexFields = parseIndexFields(options);
var typeKey = schema.options.typeKey;
var mongooseMajorVersion = +mongoose.version[0]; // 4, 5...
var mainUpdateMethod = mongooseMajorVersion < 5 ? 'update' : 'updateMany';
var mainUpdateWithDeletedMethod = mainUpdateMethod + 'WithDeleted';
function updateDocumentsByQuery(schema, conditions, updateQuery, callback) {
if (schema[mainUpdateWithDeletedMethod]) {
return schema[mainUpdateWithDeletedMethod](conditions, updateQuery, { multi: true }, callback);
} else {
return schema[mainUpdateMethod](conditions, updateQuery, { multi: true }, callback);
}
}
schema.add({ deleted: createSchemaObject(typeKey, Boolean, { default: false, index: indexFields.deleted }) });
if (options.deletedAt === true) {
schema.add({ deletedAt: createSchemaObject(typeKey, Date, { index: indexFields.deletedAt }) });
}
if (options.deletedBy === true) {
schema.add({ deletedBy: createSchemaObject(typeKey, options.deletedByType || Schema.Types.ObjectId, { index: indexFields.deletedBy }) });
}
var use$neOperator = true;
if (options.use$neOperator !== undefined && typeof options.use$neOperator === "boolean") {
use$neOperator = options.use$neOperator;
}
schema.pre('save', function (next) {
if (!this.deleted) {
this.deleted = false;
}
next();
});
if (options.overrideMethods) {
var overrideItems = options.overrideMethods;
var overridableMethods = ['count', 'countDocuments', 'find', 'findOne', 'findOneAndUpdate', 'update', 'updateOne', 'updateMany', 'aggregate'];
var finalList = [];
if ((typeof overrideItems === 'string' || overrideItems instanceof String) && overrideItems === 'all') {
finalList = overridableMethods;
}
if (typeof(overrideItems) === "boolean" && overrideItems === true) {
finalList = overridableMethods;
}
if (Array.isArray(overrideItems)) {
overrideItems.forEach(function(method) {
if (overridableMethods.indexOf(method) > -1) {
finalList.push(method);
}
});
}
if (finalList.indexOf('aggregate') > -1) {
schema.pre('aggregate', function() {
var firstMatch = this.pipeline()[0];
if(firstMatch.$match?.deleted?.$ne !== false){
if(firstMatch.$match?.showAllDocuments === 'true'){
var {showAllDocuments, ...replacement} = firstMatch.$match;
this.pipeline().shift();
if(Object.keys(replacement).length > 0){
this.pipeline().unshift({ $match: replacement });
}
}else{
this.pipeline().unshift({ $match: { deleted: { '$ne': true } } });
}
}
});
}
finalList.forEach(function(method) {
if (['count', 'countDocuments', 'find', 'findOne'].indexOf(method) > -1) {
var modelMethodName = method;
schema.statics[method] = function () {
var query = Model[modelMethodName].apply(this, arguments);
if (!arguments[2] || arguments[2].withDeleted !== true) {
if (use$neOperator) {
query.where('deleted').ne(true);
} else {
query.where({deleted: false});
}
}
return query;
};
schema.statics[method + 'Deleted'] = function () {
if (use$neOperator) {
return Model[modelMethodName].apply(this, arguments).where('deleted').ne(false);
} else {
return Model[modelMethodName].apply(this, arguments).where({deleted: true});
}
};
schema.statics[method + 'WithDeleted'] = function () {
return Model[modelMethodName].apply(this, arguments);
};
} else {
if (method === 'aggregate') {
schema.statics[method + 'Deleted'] = function () {
var args = [];
Array.prototype.push.apply(args, arguments);
var match = { $match : { deleted : {'$ne': false } } };
arguments.length ? args[0].unshift(match) : args.push([match]);
return Model[method].apply(this, args);
};
schema.statics[method + 'WithDeleted'] = function () {
var args = [];
Array.prototype.push.apply(args, arguments);
var match = { $match : { showAllDocuments : 'true' } };
arguments.length ? args[0].unshift(match) : args.push([match]);
return Model[method].apply(this, args);
};
} else {
schema.statics[method] = function () {
var args = parseUpdateArguments.apply(undefined, arguments);
if (use$neOperator) {
args[0].deleted = {'$ne': true};
} else {
args[0].deleted = false;
}
return Model[method].apply(this, args);
};
schema.statics[method + 'Deleted'] = function () {
var args = parseUpdateArguments.apply(undefined, arguments);
if (use$neOperator) {
args[0].deleted = {'$ne': false};
} else {
args[0].deleted = true;
}
return Model[method].apply(this, args);
};
schema.statics[method + 'WithDeleted'] = function () {
return Model[method].apply(this, arguments);
};
}
}
});
}
schema.methods.delete = function (deletedBy, cb) {
if (typeof deletedBy === 'function') {
cb = deletedBy;
deletedBy = null;
}
this.deleted = true;
if (schema.path('deletedAt')) {
this.deletedAt = new Date();
}
if (schema.path('deletedBy')) {
this.deletedBy = deletedBy;
}
if (options.validateBeforeDelete === false) {
return this.save({ validateBeforeSave: false }, cb);
}
return this.save(cb);
};
schema.statics.delete = function (conditions, deletedBy, callback) {
if (typeof deletedBy === 'function') {
callback = deletedBy;
conditions = conditions;
deletedBy = null;
} else if (typeof conditions === 'function') {
callback = conditions;
conditions = {};
deletedBy = null;
}
var doc = {
deleted: true
};
if (schema.path('deletedAt')) {
doc.deletedAt = new Date();
}
if (schema.path('deletedBy')) {
doc.deletedBy = deletedBy;
}
return updateDocumentsByQuery(this, conditions, doc, callback);
};
schema.statics.deleteById = function (id, deletedBy, callback) {
if (arguments.length === 0 || typeof id === 'function') {
var msg = 'First argument is mandatory and must not be a function.';
throw new TypeError(msg);
}
var conditions = {
_id: id
};
return this.delete(conditions, deletedBy, callback);
};
schema.methods.restore = function (callback) {
this.deleted = false;
this.deletedAt = undefined;
this.deletedBy = undefined;
if (options.validateBeforeRestore === false) {
return this.save({ validateBeforeSave: false }, callback);
}
return this.save(callback);
};
schema.statics.restore = function (conditions, callback) {
if (typeof conditions === 'function') {
callback = conditions;
conditions = {};
}
var doc = {
$unset:{
deleted: true,
deletedAt: true,
deletedBy: true
}
};
return updateDocumentsByQuery(this, conditions, doc, callback);
};
};