forked from dsanel/mongoose-delete
/
index.js
304 lines (256 loc) · 10.6 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
var mongoose = require('mongoose'),
Model = mongoose.Model;
/**
* 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;
}
/**
* Parses the index fields from the provided options.
*
* @param {Object} options - The options to parse index fields from.
* @param {string|boolean|Array} [options.indexFields] - The fields to index. Accepts a string, a boolean, or an array.
* If a string is provided and is 'all', all index fields are set to true.
* If a boolean is provided and is true, all index fields are set to true.
* If an array is provided, index fields are set to true if their names are included in the array.
*
* @returns {Object} The parsed index fields. Includes the following properties:
* - deleted {boolean} - Whether to index the 'deleted' field.
* - deletedAt {boolean} - Whether to index the 'deletedAt' field.
* - deletedBy {boolean} - Whether to index the 'deletedBy' field.
*
* @throws {TypeError} If options.indexFields is provided and is not a string, a boolean, or an array.
*/
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 mainUpdateWithDeletedMethod = 'updateManyWithDeleted';
function updateDocumentsByQuery(schema, conditions, updateQuery) {
if (schema['updateManyWithDeleted']) {
return schema['updateManyWithDeleted'](conditions, updateQuery, { multi: true });
} else {
return schema['updateMany'](conditions, updateQuery, { multi: true });
}
}
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: {
[typeKey]: options.deletedByType || mongoose.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', '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 firsMatchStr = JSON.stringify(this.pipeline()[0]);
if ( firsMatchStr !== '{"$match":{"deleted":{"$ne":false}}}' ) {
if (firsMatchStr === '{"$match":{"showAllDocuments":"true"}}') {
this.pipeline().shift();
} 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) {
this.deleted = true;
if (schema.path('deletedAt')) {
// TODO: Allow custom method for deletedAt
this.deletedAt = new Date();
}
if (schema.path('deletedBy')) {
this.deletedBy = deletedBy;
}
if (options.validateBeforeDelete === false) {
return this.save({ validateBeforeSave: false });
}
return this.save();
};
schema.statics.deleteMany = function (conditions, deletedBy) {
var doc = {
deleted: true
};
if (schema.path('deletedAt')) {
doc.deletedAt = new Date();
}
if (schema.path('deletedBy')) {
doc.deletedBy = deletedBy;
}
// TODO: we need to check a way to return the deleted response { acknowledged, deletedCount }
return updateDocumentsByQuery(this, conditions, doc);
};
schema.statics.deleteById = function (id, deletedBy) {
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.deleteMany(conditions, deletedBy);
};
schema.statics.restoreMany = function (conditions) {
var doc = {
deleted: false,
$unset: {
deletedAt: 1,
deletedBy: 1
}
};
return updateDocumentsByQuery(this, conditions, doc);
};
};