-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
548 lines (488 loc) · 14.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
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
const { MongoClient, ObjectId } = require('mongodb')
const cuid = require('cuid')
const lodash = require('lodash')
const extras = require('extras')
const DEFAULT_CONFIG = {
url: 'mongodb://localhost:27017',
name: 'wdb',
timestamps: true,
id: cuid,
simpleid: true,
stringid: true,
batchsize: 1000,
quiet: false
}
const DEFAULT_TIMESTAMPS = { create: 'created_at', update: 'updated_at' }
const DB_FIELD_UPDATE_OPERATORS = ['$inc', '$min', '$max', '$mul']
const DBOPTIONS = ['fields', 'limit', 'skip', 'sort']
// Parse options
function parseOptions(obj) {
for (const key in obj) {
if (typeof obj[key] == 'undefined') {
delete obj[key]
}
}
if (typeof obj.limit != 'number' || obj.limit < 1) {
delete obj.limit
}
if (typeof obj.skip != 'number' || obj.skip < 0) {
delete obj.skip
}
}
// Support alternative query
function parseQuery(obj) {
if (typeof obj == 'string') {
return { id: obj }
}
if (Array.isArray(obj)) {
return { id: { $in: obj } }
}
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => {
if (v === null) {
return [k, { $type: 10 }]
} else if (v === undefined) {
return [k, { $exists: false }]
}
return [k, v]
})
)
}
// Parse update values
function parseValues(obj, simpleid) {
obj = lodash.cloneDeep(obj)
if (obj._id) delete obj._id
if (obj.updated_at) delete obj.updated_at
if (simpleid && obj.id) delete obj.id
return obj
}
// Recursively remove undefined
function denullify(obj) {
Object.keys(obj).forEach((key) => {
if (obj[key] && typeof obj[key] === 'object') {
denullify(obj[key])
} else if (obj[key] === undefined) {
delete obj[key]
}
})
}
// Turn _id to id and reverse
function flipid(obj, out = false) {
Object.keys(obj).forEach((key) => {
if (key === '_id' && out) {
obj.id = obj._id
delete obj._id
} else if (key === 'id' && !out) {
obj._id = obj.id
delete obj.id
}
if (obj[key] && typeof obj[key] === 'object') {
flipid(obj[key], out)
}
})
}
// Helper for function parameters
function pull(args) {
let [query, options, callback] = args
if (typeof query == 'function') {
callback = query
query = options = {}
} else if (typeof options == 'function') {
callback = options
options = {}
}
return [query, options, callback]
}
module.exports = async function (config = {}) {
if (typeof config == 'string') {
config = { name: config }
}
config = lodash.merge({}, DEFAULT_CONFIG, config)
if (config.timestamps === true) {
config.timestamps = DEFAULT_TIMESTAMPS
}
config.quiet = !!process.env.MONGOWAVE_OPTIONS_QUIET || !!config.quiet
const client = new MongoClient(config.url, config.connection)
await client.connect()
const base = client.db(config.name)
function db(model) {
const collection = base.collection(model)
const getCursor = function (query, options) {
let cursor = collection.find(query)
cursor.fields = cursor.project
for (const opt in options) {
if (DBOPTIONS.includes(opt)) {
cursor = cursor[opt](options[opt])
}
}
return cursor
}
// Finds data all in one go
async function find(query = {}, options = {}) {
query = parseQuery(query)
if (config.simpleid) flipid(query)
parseOptions(options)
const result = await getCursor(query, options).toArray()
denullify(result)
if (config.simpleid) flipid(result, true)
return result
}
// Find as aggregate
async function aggregate(pipeline = [], options = {}) {
if (config.simpleid) flipid(pipeline)
parseOptions(options)
const result = await collection.aggregate(pipeline, options).toArray()
denullify(result)
if (config.simpleid) flipid(result, true)
return result
}
// Batched find for large datasets
async function search(...args) {
const [query, options, callback] = pull(args)
if (config.simpleid) flipid(query)
parseOptions(options)
const size = options.size || config.batchsize
const limit = options.limit || size
const total = await count(query, { limit: options.limit })
const add = typeof options.limit == 'undefined' ? 1 : 0
const pages = parseInt(total / limit) + add
let c = 0
for (let page = 0; page < pages; page++) {
const result = await find(query, {
sort: options.sort,
skip: page * limit,
limit,
fields: options.fields
})
denullify(result)
if (config.simpleid) flipid(result, true)
c += result.length
if (typeof callback == 'function') {
const percent = ((page / pages) * 100).toFixed(2)
await callback(result, {
total,
page,
pages,
count: c,
percent
})
}
}
}
// Faster batched find for smaller datasets
async function batch(...args) {
const [query, options, callback] = pull(args)
if (config.simpleid) flipid(query)
parseOptions(options)
const size = options.size || config.batchsize
const quiet = options.quiet || config.quiet
const sync = options.sync || config.sync
delete options.size
delete options.quiet
delete options.sync
// Fetch ids
const all = await find(query, {
sort: options.sort,
limit: options.limit,
fields: { id: 1 }
})
const total = all.length
const pages = parseInt(total / size) + 1
let count = 0
for (let page = 1; page <= pages; page++) {
const ids = all.slice(count, page * size).map((x) => x.id)
const result = await find(
{ id: { $in: ids } },
{
fields: options.fields
}
)
denullify(result)
if (config.simpleid) flipid(result, true)
count += result.length
if (typeof callback == 'function') {
const percent = ((page / pages) * 100).toFixed(2)
if (!quiet) {
extras.print(`${percent}% ${total} ${page}/${pages}`)
}
if (sync) {
await Promise.all(result.map(callback))
} else {
await callback(result, {
total,
page,
pages,
count,
percent
})
}
}
}
}
// Find one by one
async function each(...args) {
const [query, options, callback] = pull(args)
if (config.simpleid) flipid(query)
parseOptions(options)
var callbacks = []
await getCursor(query, options).forEach(async function (result) {
denullify(result)
if (config.simpleid) flipid(result, true)
if (typeof callback == 'function') {
callbacks.push(callback(result))
}
})
await Promise.all(callbacks)
}
// Find only one
async function get(query = {}, options = {}) {
var result = await find(query, { ...options, limit: 1 })
return result[0] || null
}
// Find first created
async function first(query = {}) {
return get(query, { sort: { created_at: 1 } })
}
// Find last created
async function last(query = {}) {
return get(query, { sort: { created_at: -1 } })
}
// Find last updated
async function changed(query = {}) {
return get(query, { sort: { updated_at: -1 } })
}
// Find ids
async function ids(query = {}) {
var result = await find(query, { fields: { id: 1 } })
return result.map((x) => x.id)
}
// Count
async function count(query = {}, options = {}) {
query = parseQuery(query)
if (config.simpleid) flipid(query)
parseOptions(options)
return await collection.countDocuments(query, options)
}
// Create
async function create(values = {}, options = {}) {
values = lodash.cloneDeep(values)
const wasArray = Array.isArray(values)
denullify(values)
if (!wasArray) values = [values]
if (config.simpleid) flipid(values)
for (const val of values) {
if (config.id) {
val._id = val._id || val.id || config.id()
if (config.stringid) val._id = String(val._id)
}
const { create, update } = config.timestamps
const date = new Date()
if (create && typeof val[create] == 'undefined') {
val[create] = date
}
if (update && typeof val[update] == 'undefined') {
val[update] = date
}
}
parseOptions(options)
await collection.insertMany(values, options)
if (config.simpleid) flipid(values, true)
return wasArray ? values : values[0]
}
// Update
async function update(query = {}, values = {}, options = {}) {
query = parseQuery(query)
if (config.simpleid) flipid(query)
values = parseValues(values, config.simpleid)
parseOptions(options)
const operation = {}
for (const key in values) {
if (DB_FIELD_UPDATE_OPERATORS.includes(key)) {
operation[key] = values[key]
delete values[key]
} else if (values[key] === undefined) {
if (!operation.$unset) operation.$unset = {}
operation.$unset[key] = ''
} else {
if (!operation.$set) operation.$set = {}
operation.$set[key] = values[key]
}
}
if (!Object.keys(operation).length) return { n: 0 }
const { update } = config.timestamps
if (update && (operation.$set || operation.$unset)) {
if (!operation.$set) operation.$set = {}
operation.$set[update] = new Date()
}
const result = await collection.updateMany(query, operation, options)
return { n: result.modifiedCount }
}
// Upsert
async function upsert(query = {}, values = {}) {
var existing = await get(query)
if (existing) {
await update(existing.id, values)
return await get(existing.id)
}
return await create(values)
}
// Replace
async function replace(query = {}, values = {}, options = {}) {
query = parseQuery(query)
if (config.simpleid) flipid(query)
values = parseValues(values, config.simpleid)
denullify(values)
parseOptions(options)
const result = await collection.replaceOne(query, values, options)
return { n: result.modifiedCount }
}
// Repsert
async function repsert(query = {}, values = {}) {
var existing = await get(query)
if (existing) {
await replace(existing.id, values)
return await get(existing.id)
}
return await create(values)
}
// Delete
async function del(query = {}, options = {}) {
query = parseQuery(query)
if (config.simpleid) flipid(query)
parseOptions(options)
const result = await collection.deleteMany(query, options)
return { n: result.deletedCount }
}
// Set, alternative to create, update and delete
async function set(query = {}, values) {
if (values === null) {
return await del(query)
} else if (values) {
return await update(query, values)
} else {
return await create(query)
}
}
// Experimental duplicate checker
async function dups(opt = {}) {
if (!opt.fields) opt.fields = []
var d = new Set()
async function check(doc) {
var query = {}
for (var field of opt.fields) {
query[field] = doc[field]
}
var list = (await ids(query)).sort()
if (list.length > 1) {
d.add(list.join('|'))
}
}
await batch(async function (docs) {
await Promise.all(docs.map(check))
})
return [...d].map((x) => x.split('|'))
}
// Experimental analyzer for queries
async function analyze(query = {}, options = {}, silent) {
var result = await collection.find(query, options).explain()
!silent && console.info(JSON.stringify(result, null, 2))
const { queryPlanner, executionStats } = result
!silent &&
console.info(
`Returned ${executionStats.nReturned} documents in ${
executionStats.executionTimeMillis / 1000
}s.`
)
// totalDocsExamined should be 0 if indexes cover the search
!silent &&
console.info(`Total docs examined: ${executionStats.totalDocsExamined}`)
function trace(plan) {
const stages = [plan.stage]
let inputStage = plan.inputStage
if (inputStage) {
do {
stages.push(inputStage.stage)
} while ((inputStage = inputStage.inputStage))
}
return stages
}
const stages = trace(queryPlanner.winningPlan)
!silent && console.info({ stages })
const BADCODES = ['FETCH', 'COLLSCAN']
const failed = stages.find((x) => BADCODES.includes(x))
if (failed) {
!silent && console.info(`Index missing for query:`)
!silent &&
console.info(JSON.stringify({ model, query, options }, null, 2))
} else {
!silent && console.info('Index for this query is good!')
}
return { model, query, options, result, stages, failed }
}
return {
find,
aggregate,
search,
batch,
each,
get,
first,
last,
changed,
ids,
count,
create,
update,
upsert,
replace,
repsert,
delete: del,
set,
dups,
analyze
}
}
db.client = client
db.base = base
db.id = ObjectId
// List all collections for a database
db.collections = function () {
return base.listCollections().toArray()
}
// Add indexes
db.index = async function (indexes = {}) {
for (const collection in indexes) {
const index = indexes[collection]
for (const values of index) {
const [fields, options] = values
try {
console.info('Adding index to', collection)
console.info(JSON.stringify(fields, null, 2))
console.info(JSON.stringify(options || {}, null, 2))
await base.collection(collection).createIndex(fields, options)
} catch (e) {
console.info(e.message)
}
}
}
}
// Drop indexes
db.deindex = async function (collections) {
if (!collections) {
collections = (await db.collections()).map((c) => c.name)
}
for (const collection of collections) {
try {
await base.collection(collection).dropIndexes()
} catch (e) {
console.info(e.message)
}
}
}
// Drop database
db.drop = async function () {
await db.deindex()
return base.dropDatabase()
}
return db
}