-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathindex.js
More file actions
528 lines (465 loc) · 11.6 KB
/
index.js
File metadata and controls
528 lines (465 loc) · 11.6 KB
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
/*
* moleculer-db-adapter-mongoose
* Copyright (c) 2019 MoleculerJS (https://github.com/moleculerjs/moleculer-db)
* MIT Licensed
*/
"use strict";
const _ = require("lodash");
const { ServiceSchemaError, MoleculerError } = require("moleculer").Errors;
const mongoose = require("mongoose");
mongoose.set("strictQuery", true);
class MongooseDbAdapter {
/**
* Creates an instance of MongooseDbAdapter.
* @param {String} uri
* @param {Object?} opts
*
* @memberof MongooseDbAdapter
*/
constructor(uri, opts) {
this.uri = uri;
this.opts = opts;
}
/**
* Initialize adapter
*
* @param {ServiceBroker} broker
* @param {Service} service
*
* @memberof MongooseDbAdapter
*/
init(broker, service) {
this.broker = broker;
this.service = service;
this.useNativeMongooseVirtuals = !!service.settings?.useNativeMongooseVirtuals;
if (this.service.schema.model) {
this.model = this.service.schema.model;
} else if (this.service.schema.schema) {
if (!this.service.schema.modelName) {
throw new ServiceSchemaError("`modelName` is required when `schema` is given in schema of service!");
}
this.schema = this.service.schema.schema;
this.modelName = this.service.schema.modelName;
}
if (!this.model && !this.schema) {
/* istanbul ignore next */
throw new ServiceSchemaError("Missing `model` or `schema` definition in schema of service!");
}
}
/**
* Connect to database
*
* @returns {Promise}
*
* @memberof MongooseDbAdapter
*/
connect() {
let conn;
if (this.model) {
/* istanbul ignore next */
if (mongoose.connection.readyState == 1) {
this.db = mongoose.connection;
return Promise.resolve();
} else if (mongoose.connection.readyState == 2) {
conn = mongoose.connection.asPromise();
} else {
conn = mongoose.connect(this.uri, this.opts);
}
} else if (this.schema) {
conn = new Promise(resolve =>{
const c = mongoose.createConnection(this.uri, this.opts);
this.model = c.model(this.modelName, this.schema);
resolve(c);
});
}
return conn.then(() => {
this.conn = mongoose.connection;
if (mongoose.connection.readyState != mongoose.connection.states.connected) {
throw new MoleculerError(
`MongoDB connection failed . Status is "${
mongoose.connection.states[mongoose.connection._readyState]
}"`
);
}
if(!this.model) {
this.model = mongoose.model(this.model["modelName"],this.model["schema"]);
}
this.db = mongoose.connection.db;
if (!this.db) {
throw new MoleculerError("MongoDB connection failed to get DB object");
}
this.service.logger.info("MongoDB adapter has connected successfully.");
/* istanbul ignore next */
mongoose.connection.on("disconnected", () => this.service.logger.warn("Mongoose adapter has disconnected."));
mongoose.connection.on("error", err => this.service.logger.error("MongoDB error.", err));
mongoose.connection.on("reconnect", () => this.service.logger.info("Mongoose adapter has reconnected."));
});
}
/**
* Disconnect from database
*
* @returns {Promise}
*
* @memberof MongooseDbAdapter
*/
disconnect() {
return new Promise(resolve => {
if (this.db && this.db.close) {
this.db.close(resolve);
} else if (this.conn && this.conn.close) {
this.conn.close(resolve);
} else {
mongoose.connection.close(resolve);
}
});
}
/**
* Find all entities by filters.
*
* Available filter props:
* - limit
* - offset
* - sort
* - search
* - searchFields
* - query
*
* @param {any} filters
* @returns {Promise}
*
* @memberof MongooseDbAdapter
*/
find(filters) {
return this.createCursor(filters).exec();
}
/**
* Find an entity by query
*
* @param {Object} query
* @returns {Promise}
* @memberof MemoryDbAdapter
*/
findOne(query) {
return this.model.findOne(query).exec();
}
/**
* Find an entities by ID
*
* @param {any} _id
* @returns {Promise}
*
* @memberof MongooseDbAdapter
*/
findById(_id) {
return this.model.findById(_id).exec();
}
/**
* Find any entities by IDs
*
* @param {Array} idList
* @returns {Promise}
*
* @memberof MongooseDbAdapter
*/
findByIds(idList) {
return this.model.find({
_id: {
$in: idList
}
}).exec();
}
/**
* Get count of filtered entites
*
* Available filter props:
* - search
* - searchFields
* - query
*
* @param {Object} [filters={}]
* @returns {Promise}
*
* @memberof MongooseDbAdapter
*/
count(filters = {}) {
return this.createCursor(filters).countDocuments().exec();
}
/**
* Insert an entity
*
* @param {Object} entity
* @returns {Promise}
*
* @memberof MongooseDbAdapter
*/
insert(entity) {
const item = new this.model(entity);
return item.save();
}
/**
* Insert many entities
*
* @param {Array} entities
* @returns {Promise}
*
* @memberof MongooseDbAdapter
*/
insertMany(entities) {
return this.model.create(entities);
}
/**
* Update many entities by `query` and `update`
*
* @param {Object} query
* @param {Object} update
* @returns {Promise}
*
* @memberof MongooseDbAdapter
*/
updateMany(query, update) {
return this.model.updateMany(query, update, { multi: true, "new": true }).then(res => {
return res.modifiedCount;
});
}
/**
* Update an entity by ID and `update`
*
* @param {any} _id
* @param {Object} update
* @returns {Promise}
*
* @memberof MongooseDbAdapter
*/
updateById(_id, update) {
return this.model.findByIdAndUpdate(_id, update, { "new": true });
}
/**
* Remove entities which are matched by `query`
*
* @param {Object} query
* @returns {Promise}
*
* @memberof MongooseDbAdapter
*/
removeMany(query) {
return this.model.deleteMany(query).then(res => {
return res.deletedCount;
});
}
/**
* Remove an entity by ID
*
* @param {any} _id
* @returns {Promise}
*
* @memberof MongooseDbAdapter
*/
removeById(_id) {
return this.model.findByIdAndDelete(_id);
}
/**
* Clear all entities from collection
*
* @returns {Promise}
*
* @memberof MongooseDbAdapter
*/
clear() {
return this.model.deleteMany({}).then(res => res.deletedCount);
}
/**
* Return proper query to populate virtuals depending on service populate params
*
* @param {Context} ctx - moleculer context
* @returns {Object[]}
* @memberof MongooseDbAdapter
*/
getNativeVirtualPopulateQuery(ctx) {
const fieldsToPopulate = ctx.params?.populate || [];
if (fieldsToPopulate.length === 0) return [];
const virtualFields = Object.entries( this.model?.schema?.virtuals || {})
.reduce((acc, [path, virtual]) => {
const hasRef = !!(virtual.options?.ref || virtual.options?.refPath);
const hasMatch = !! virtual.options?.match;
if (hasRef) acc[path] = hasMatch;
return acc;
}, {});
const virtualsToPopulate = _.intersection(fieldsToPopulate, Object.keys(virtualFields));
if (virtualsToPopulate.length === 0) return [];
const getPathOptions = (path) =>
_.get(ctx, `service.settings.virtuals.${path}.options`, {skipInvalidIds: true, lean: true});
const getPathTransform = (path) =>
_.get(ctx, `service.settings.virtuals.${path}.transform`, (doc) => doc._id);
const getPathSelect = (path) =>
_.get(ctx, `service.settings.virtuals.${path}.select`, _.get(virtualFields, path) ? undefined : "_id");
return virtualsToPopulate.map((path) => ({
path,
select: getPathSelect(path),
options : getPathOptions(path),
transform: getPathTransform(path)
}));
}
/**
* Replace virtuals that would trigger subqueries by the localField
* they target to be used later in action propagation
*
* @param {Context} ctx - moleculer context
* @param {Object} json - the JSONified entity
* @returns {Object}
* @memberof MongooseDbAdapter
*/
mapVirtualsToLocalFields(ctx, json) {
Object.entries(this.model?.schema?.virtuals || {})
.forEach(([path, virtual]) => {
const localField = virtual.options?.localField;
if (localField) json[path] = json[localField];
});
}
/**
* Convert DB entity to JSON object
*
* @param {any} entity
* @param {Context} ctx - moleculer context
* @returns {Object}
* @memberof MongooseDbAdapter
*/
entityToObject(entity, ctx) {
const populate = this.useNativeMongooseVirtuals ? this.getNativeVirtualPopulateQuery(ctx) : [];
return Promise.resolve(populate.length > 0 ? entity.populate(populate) : entity)
.then(entity => {
const json = entity.toJSON();
if (entity._id && entity._id.toHexString) {
json._id = entity._id.toHexString();
} else if (entity._id && entity._id.toString) {
json._id = entity._id.toString();
}
if (!this.useNativeMongooseVirtuals) {
this.mapVirtualsToLocalFields(ctx, json);
}
return json;
});
}
/**
* Create a filtered query
* Available filters in `params`:
* - search
* - sort
* - limit
* - offset
* - query
*
* @param {Object} params
* @returns {MongoQuery}
*/
createCursor(params) {
if (params) {
const q = this.model.find(params.query);
// Search
if (_.isString(params.search) && params.search !== "") {
if (params.searchFields && params.searchFields.length > 0) {
const searchQuery = {
$or: params.searchFields.map(f => (
{
[f]: new RegExp(_.escapeRegExp(params.search), "i")
}
))
};
const query = q.getQuery();
if (query.$or) {
if (!Array.isArray(query.$and)) query.$and = [];
query.$and.push(
_.pick(query, "$or"),
searchQuery
);
q.setQuery(_.omit(query, "$or"));
} else {
q.find(searchQuery);
}
} else {
// Full-text search
// More info: https://docs.mongodb.com/manual/reference/operator/query/text/
q.find({
$text: {
$search: params.search
}
});
q._fields = {
_score: {
$meta: "textScore"
}
};
q.sort({
_score: {
$meta: "textScore"
}
});
}
}
// Sort
if (_.isString(params.sort))
q.sort(params.sort.replace(/,/, " "));
else if (Array.isArray(params.sort))
q.sort(params.sort.join(" "));
// Offset
if (_.isNumber(params.offset) && params.offset > 0)
q.skip(params.offset);
// Limit
if (_.isNumber(params.limit) && params.limit > 0)
q.limit(params.limit);
return q;
}
return this.model.find();
}
/**
* Transforms 'idField' into MongoDB's '_id'
* @param {Object} entity
* @param {String} idField
* @memberof MongoDbAdapter
* @returns {Object} Modified entity
*/
beforeSaveTransformID (entity, idField) {
let newEntity = _.cloneDeep(entity);
if (idField !== "_id" && entity[idField] !== undefined) {
newEntity._id = this.stringToObjectID(newEntity[idField]);
delete newEntity[idField];
}
return newEntity;
}
/**
* Transforms MongoDB's '_id' into user defined 'idField'
* @param {Object} entity
* @param {String} idField
* @memberof MongoDbAdapter
* @returns {Object} Modified entity
*/
afterRetrieveTransformID (entity, idField) {
if (idField !== "_id") {
entity[idField] = this.objectIDToString(entity["_id"]);
delete entity._id;
}
return entity;
}
/**
* Convert hex string to ObjectID
* @param {String} id
* @returns ObjectID}
* @memberof MongooseDbAdapter
*/
stringToObjectID (id) {
if (typeof id == "string" && mongoose.Types.ObjectId.isValid(id))
return new mongoose.Schema.Types.ObjectId(id);
return id;
}
/**
* Convert ObjectID to hex string
* @param {ObjectID} id
* @returns {String}
* @memberof MongooseDbAdapter
*/
objectIDToString (id) {
if(id && id.toString)
return id.toString();
return id;
}
}
module.exports = MongooseDbAdapter;