-
Notifications
You must be signed in to change notification settings - Fork 96
/
service.js
executable file
·329 lines (274 loc) · 9.18 KB
/
service.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
322
323
324
325
326
327
328
329
const omit = require('lodash.omit');
const Proto = require('uberproto');
const { select, filterQuery } = require('@feathersjs/commons');
const errors = require('@feathersjs/errors');
const errorHandler = require('./error-handler');
// Create the service.
class Service {
constructor (options) {
if (!options) {
throw new Error('Mongoose options have to be provided');
}
if (!options.Model || !options.Model.modelName) {
throw new Error('You must provide a Mongoose Model');
}
this.Model = options.Model;
this.discriminatorKey = this.Model.schema.options.discriminatorKey;
this.discriminators = {};
(options.discriminators || []).forEach(element => {
if (element.modelName) {
this.discriminators[element.modelName] = element;
}
});
this.id = options.id || '_id';
this.paginate = options.paginate || {};
this.lean = options.lean === undefined ? true : options.lean;
this.overwrite = options.overwrite !== false;
this.events = options.events || [];
this.useEstimatedDocumentCount = !!options.useEstimatedDocumentCount;
}
extend (obj) {
return Proto.extend(obj, this);
}
_find (params, count, getFilter = filterQuery) {
const { filters, query } = getFilter(params.query || {});
const discriminator = (params.query || {})[this.discriminatorKey] || this.discriminatorKey;
const model = this.discriminators[discriminator] || this.Model;
const q = model.find(query).lean(this.lean);
// $select uses a specific find syntax, so it has to come first.
if (Array.isArray(filters.$select)) {
let fields = {};
for (let key of filters.$select) {
fields[key] = 1;
}
q.select(fields);
} else if (typeof filters.$select === 'string' || typeof filters.$select === 'object') {
q.select(filters.$select);
}
// Handle $sort
if (filters.$sort) {
q.sort(filters.$sort);
}
// Handle $limit
if (typeof filters.$limit !== 'undefined') {
q.limit(filters.$limit);
}
// Handle $skip
if (filters.$skip) {
q.skip(filters.$skip);
}
// Handle $populate
if (filters.$populate) {
q.populate(filters.$populate);
}
let executeQuery = total => {
return q.exec().then(data => {
return {
total,
limit: filters.$limit,
skip: filters.$skip || 0,
data
};
});
};
if (filters.$limit === 0) {
executeQuery = total => {
return Promise.resolve({
total,
limit: filters.$limit,
skip: filters.$skip || 0,
data: []
});
};
}
if (count) {
return model.where(query)[this.useEstimatedDocumentCount ? 'estimatedDocumentCount' : 'countDocuments']().exec().then(executeQuery);
}
return executeQuery();
}
find (params) {
const paginate = (params && typeof params.paginate !== 'undefined') ? params.paginate : this.paginate;
const result = this._find(params, !!paginate.default,
query => filterQuery(query, paginate)
);
if (!paginate.default) {
return result.then(page => page.data);
}
return result;
}
_get (id, params = {}) {
params.query = params.query || {};
const discriminator = (params.query || {})[this.discriminatorKey] || this.discriminatorKey;
const model = this.discriminators[discriminator] || this.Model;
let modelQuery = model
.findOne({ [this.id]: id });
// Handle $populate
if (params.query.$populate) {
modelQuery = modelQuery.populate(params.query.$populate);
}
// Handle $select
if (params.query.$select && params.query.$select.length) {
let fields = { [this.id]: 1 };
for (let key of params.query.$select) {
fields[key] = 1;
}
modelQuery.select(fields);
} else if (params.query.$select && typeof params.query.$select === 'object') {
modelQuery.select(params.query.$select);
}
return modelQuery
.lean(this.lean)
.exec()
.then(data => {
if (!data) {
throw new errors.NotFound(`No record found for id '${id}'`);
}
return data;
})
.catch(errorHandler);
}
get (id, params) {
return this._get(id, params);
}
_getOrFind (id, params) {
if (id === null) {
return this._find(params).then(page => page.data);
}
return this._get(id, params);
}
create (data, params) {
const discriminator = data[this.discriminatorKey] || this.discriminatorKey;
const model = this.discriminators[discriminator] || this.Model;
return model.create(data)
.then(result => {
if (this.lean) {
if (Array.isArray(result)) {
return result.map(item => (item.toObject ? item.toObject() : item));
}
return result.toObject ? result.toObject() : result;
}
return result;
})
.then(select(params, this.id))
.catch(errorHandler);
}
update (id, data, params) {
if (id === null) {
return Promise.reject(new errors.BadRequest('Not replacing multiple records. Did you mean `patch`?'));
}
// Handle case where data might be a mongoose model
if (typeof data.toObject === 'function') {
data = data.toObject();
}
const options = Object.assign({
new: true,
overwrite: this.overwrite,
runValidators: true,
context: 'query',
setDefaultsOnInsert: true
}, params.mongoose);
if (this.id === '_id') {
// We can not update default mongo ids
data = omit(data, this.id);
} else {
// If not using the default Mongo _id field set the id to its
// previous value. This prevents orphaned documents.
data = Object.assign({}, data, { [this.id]: id });
}
const discriminator = (params.query || {})[this.discriminatorKey] || this.discriminatorKey;
const model = this.discriminators[discriminator] || this.Model;
let modelQuery = model.findOneAndUpdate({ [this.id]: id }, data, options);
if (params && params.query && params.query.$populate) {
modelQuery = modelQuery.populate(params.query.$populate);
}
return modelQuery
.lean(this.lean)
.exec()
.then(select(params, this.id))
.catch(errorHandler);
}
patch (id, data, params) {
const query = Object.assign({}, filterQuery(params.query || {}).query);
const mapIds = page => page.data.map(current => current[this.id]);
// By default we will just query for the one id. For multi patch
// we create a list of the ids of all items that will be changed
// to re-query them after the update
const ids = id === null ? this._find(params)
.then(mapIds) : Promise.resolve([ id ]);
// Handle case where data might be a mongoose model
if (typeof data.toObject === 'function') {
data = data.toObject();
}
// ensure we are working on a copy
data = Object.assign({}, data);
// If we are updating multiple records
let options = Object.assign({
multi: id === null,
runValidators: true,
context: 'query'
}, params.mongoose);
if (id !== null) {
query[this.id] = id;
}
if (this.id === '_id') {
// We can not update default mongo ids
delete data[this.id];
} else if (id !== null) {
// If not using the default Mongo _id field set the id to its
// previous value. This prevents orphaned documents.
data[this.id] = id;
}
// NOTE (EK): We need this shitty hack because update doesn't
// return a promise properly when runValidators is true. WTF!
try {
return ids
.then(idList => {
// Create a new query that re-queries all ids that
// were originally changed
const findParams = idList.length ? Object.assign({}, params, {
query: {
[this.id]: { $in: idList }
}
}) : params;
if (params.query && params.query.$populate) {
findParams.query.$populate = params.query.$populate;
}
// If params.query.$populate was provided, remove it
// from the query sent to mongoose.
const discriminator = (params.query || {})[this.discriminatorKey] || this.discriminatorKey;
const model = this.discriminators[discriminator] || this.Model;
return model
.update(omit(query, '$populate'), data, options)
.lean(this.lean)
.exec()
.then(() => this._getOrFind(id, findParams));
})
.then(select(params, this.id))
.catch(errorHandler);
} catch (e) {
return errorHandler(e);
}
}
remove (id, params) {
const query = Object.assign({}, filterQuery(params.query || {}).query);
if (id !== null) {
query[this.id] = id;
}
// NOTE (EK): First fetch the record(s) so that we can return
// it/them when we delete it/them.
return this._getOrFind(id, params)
.then(data =>
this.Model
.remove(query)
.lean(this.lean)
.exec()
.then(() => data)
.then(select(params, this.id))
)
.catch(errorHandler);
}
}
module.exports = function init (options) {
return new Service(options);
};
module.exports.Service = Service;