-
Notifications
You must be signed in to change notification settings - Fork 122
/
index.js
415 lines (373 loc) · 8.89 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
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
/*
* moleculer-db-adapter-mongo
* Copyright (c) 2019 MoleculerJS (https://github.com/moleculerjs/moleculer-db)
* MIT Licensed
*/
"use strict";
const _ = require("lodash");
const { ServiceSchemaError } = require("moleculer").Errors;
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;
const ObjectID = mongodb.ObjectID;
class MongoDbAdapter {
/**
* Creates an instance of MongoDbAdapter.
* @param {String} uri
* @param {Object?} opts
* @param {String?} dbName
*
* @memberof MongoDbAdapter
*/
constructor(uri, opts, dbName) {
this.uri = uri,
this.opts = opts;
this.dbName = dbName;
}
/**
* Initialize adapter
*
* @param {ServiceBroker} broker
* @param {Service} service
*
* @memberof MongoDbAdapter
*/
init(broker, service) {
this.broker = broker;
this.service = service;
if (!this.service.schema.collection) {
/* istanbul ignore next */
throw new ServiceSchemaError("Missing `collection` definition in schema of service!");
}
}
/**
* Connect to database
*
* @returns {Promise}
*
* @memberof MongoDbAdapter
*/
connect() {
this.client = new MongoClient(this.uri, this.opts);
return this.client.connect().then(() => {
this.db = this.client.db(this.dbName);
this.collection = this.db.collection(this.service.schema.collection);
this.service.logger.info("MongoDB adapter has connected successfully.");
/* istanbul ignore next */
this.db.on("close", () => this.service.logger.warn("MongoDB adapter has disconnected."));
this.db.on("error", err => this.service.logger.error("MongoDB error.", err));
this.db.on("reconnect", () => this.service.logger.info("MongoDB adapter has reconnected."));
});
}
/**
* Disconnect from database
*
* @returns {Promise}
*
* @memberof MongoDbAdapter
*/
disconnect() {
if (this.client) {
this.client.close();
}
return Promise.resolve();
}
/**
* Find all entities by filters.
*
* Available filter props:
* - limit
* - offset
* - sort
* - search
* - searchFields
* - query
*
* @param {Object} filters
* @returns {Promise<Array>}
*
* @memberof MongoDbAdapter
*/
find(filters) {
return this.createCursor(filters, false).toArray();
}
/**
* Find an entity by query
*
* @param {Object} query
* @returns {Promise}
* @memberof MemoryDbAdapter
*/
findOne(query) {
return this.collection.findOne(query);
}
/**
* Find an entities by ID.
*
* @param {String} _id
* @returns {Promise<Object>} Return with the found document.
*
* @memberof MongoDbAdapter
*/
findById(_id) {
return this.collection.findOne({ _id: this.stringToObjectID(_id) });
}
/**
* Find any entities by IDs.
*
* @param {Array} idList
* @returns {Promise<Array>} Return with the found documents in an Array.
*
* @memberof MongoDbAdapter
*/
findByIds(idList) {
return this.collection.find({
_id: {
$in: idList.map(id => this.stringToObjectID(id))
}
}).toArray();
}
/**
* Get count of filtered entites.
*
* Available query props:
* - search
* - searchFields
* - query
*
* @param {Object} [filters={}]
* @returns {Promise<Number>} Return with the count of documents.
*
* @memberof MongoDbAdapter
*/
count(filters = {}) {
return this.createCursor(filters, true);
}
/**
* Insert an entity.
*
* @param {Object} entity
* @returns {Promise<Object>} Return with the inserted document.
*
* @memberof MongoDbAdapter
*/
insert(entity) {
return this.collection.insertOne(entity).then(res => {
if (res.insertedCount > 0)
return res.ops[0];
});
}
/**
* Insert many entities
*
* @param {Array} entities
* @returns {Promise<Array<Object>>} Return with the inserted documents in an Array.
*
* @memberof MongoDbAdapter
*/
insertMany(entities) {
return this.collection.insertMany(entities).then(res => res.ops);
}
/**
* Update many entities by `query` and `update`
*
* @param {Object} query
* @param {Object} update
* @returns {Promise<Number>} Return with the count of modified documents.
*
* @memberof MongoDbAdapter
*/
updateMany(query, update) {
return this.collection.updateMany(query, update).then(res => res.modifiedCount);
}
/**
* Update an entity by ID and `update`
*
* @param {String} _id - ObjectID as hexadecimal string.
* @param {Object} update
* @returns {Promise<Object>} Return with the updated document.
*
* @memberof MongoDbAdapter
*/
updateById(_id, update) {
return this.collection.findOneAndUpdate({ _id: this.stringToObjectID(_id) }, update, { returnOriginal : false }).then(res => res.value);
}
/**
* Remove entities which are matched by `query`
*
* @param {Object} query
* @returns {Promise<Number>} Return with the count of deleted documents.
*
* @memberof MongoDbAdapter
*/
removeMany(query) {
return this.collection.deleteMany(query).then(res => res.deletedCount);
}
/**
* Remove an entity by ID
*
* @param {String} _id - ObjectID as hexadecimal string.
* @returns {Promise<Object>} Return with the removed document.
*
* @memberof MongoDbAdapter
*/
removeById(_id) {
return this.collection.findOneAndDelete({ _id: this.stringToObjectID(_id) }).then(res => res.value);
}
/**
* Clear all entities from collection
*
* @returns {Promise}
*
* @memberof MongoDbAdapter
*/
clear() {
return this.collection.deleteMany({}).then(res => res.deletedCount);
}
/**
* Convert DB entity to JSON object. It converts the `_id` to hexadecimal `String`.
*
* @param {Object} entity
* @returns {Object}
* @memberof MongoDbAdapter
*/
entityToObject(entity) {
const json = Object.assign({}, entity);
if (entity._id)
json._id = this.objectIDToString(entity._id);
return json;
}
/**
* Create a filtered cursor.
*
* Available filters in `params`:
* - search
* - sort
* - limit
* - offset
* - query
*
* @param {Object} params
* @param {Boolean} isCounting
* @returns {MongoCursor}
*/
createCursor(params, isCounting) {
const fn = isCounting ? this.collection.countDocuments : this.collection.find;
let q;
if (params) {
// Full-text search
// More info: https://docs.mongodb.com/manual/reference/operator/query/text/
if (_.isString(params.search) && params.search !== "") {
q = fn.call(this.collection, Object.assign(params.query || {}, {
$text: {
$search: params.search
}
}));
if (q.project && !isCounting)
q.project({ _score: { $meta: "textScore" } });
if (q.sort && !isCounting) {
q.sort({
_score: {
$meta: "textScore"
}
});
}
} else {
q = fn.call(this.collection, params.query);
// Sort
if (params.sort && q.sort) {
const sort = this.transformSort(params.sort);
if (sort)
q.sort(sort);
}
}
// 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;
}
// If not params
return fn.call(this.collection, {});
}
/**
* Convert the `sort` param to a `sort` object to Mongo queries.
*
* @param {String|Array<String>|Object} paramSort
* @returns {Object} Return with a sort object like `{ "votes": 1, "title": -1 }`
* @memberof MongoDbAdapter
*/
transformSort(paramSort) {
let sort = paramSort;
if (_.isString(sort))
sort = sort.replace(/,/, " ").split(" ");
if (Array.isArray(sort)) {
const sortObj = {};
sort.forEach(s => {
if (s.startsWith("-"))
sortObj[s.slice(1)] = -1;
else
sortObj[s] = 1;
});
return sortObj;
}
return sort;
}
/**
* Convert hex string to ObjectID
*
* @param {String} id
* @returns {ObjectID}
*
* @memberof MongoDbAdapter
*/
stringToObjectID(id) {
if (typeof id == "string" && id.length !== 12 && ObjectID.isValid(id))
return new ObjectID.createFromHexString(id);
return id;
}
/**
* Convert ObjectID to Hex string
*
* @param {ObjectID} id
* @returns {String}
*
* @memberof MongoDbAdapter
*/
objectIDToString(id) {
if (id && id.toHexString)
return id.toHexString();
return id;
}
/**
* Transforms 'idField' into MongoDB's '_id'
* @param {Object} entity
* @param {String} idField
* @memberof MongoDbAdapter
* @returns {Object} Modified entity
*/
beforeSaveTransformID (entity, idField) {
const 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;
}
}
module.exports = MongoDbAdapter;