-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCrudService.js
641 lines (516 loc) · 20.4 KB
/
CrudService.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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
/*
* Copyright 2023 Mia s.r.l.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict'
const assert = require('assert')
const { get: lget, unset: lunset } = require('lodash')
const {
UPDATERID,
UPDATEDAT,
CREATORID,
CREATEDAT,
__STATE__,
STATES: { PUBLIC, DRAFT, TRASH, DELETED },
textScore,
SETCMD,
UNSETCMD,
INCCMD,
MULCMD,
CURDATECMD,
SETONINSERTCMD,
PUSHCMD,
ADDTOSETCMD,
PULLCMD,
QUERY,
STATE,
} = require('./consts')
const { getStateQuery } = require('./CrudService.utils')
const { JSONPath } = require('jsonpath-plus')
const { getPathFromPointer } = require('./JSONPath.utils')
const resolveMongoQuery = require('./resolveMongoQuery')
const ALLOWED_COMMANDS = [
SETCMD,
INCCMD,
MULCMD,
CURDATECMD,
SETONINSERTCMD,
UNSETCMD,
PUSHCMD,
PULLCMD,
ADDTOSETCMD,
]
const STANDARD_FIELDS = [
UPDATERID,
UPDATEDAT,
CREATORID,
CREATEDAT,
]
/**
* List of states available for a document managed by the CRUD Service
* and the possible states it can start from, based on requested operations
*/
const STATES_FINITE_STATE_MACHINE = {
[PUBLIC]: [DRAFT],
[DRAFT]: [PUBLIC, TRASH],
[TRASH]: [PUBLIC, DRAFT, DELETED],
[DELETED]: [TRASH],
}
/**
* List of status available for a document managed by the CRUD Service
* and the possible states it can move to, based on the requested operations
*/
const ALLOWED_STATES_MAP = {
[PUBLIC]: [DRAFT, PUBLIC, TRASH],
[DRAFT]: [DRAFT, PUBLIC, TRASH],
[TRASH]: [DELETED, DRAFT, TRASH],
[DELETED]: [DELETED, TRASH],
}
const NO_DOCUMENT_FOUND = '<no document found>'
function getQueryOptions(crudServiceOptions) {
const options = {}
if (crudServiceOptions.allowDiskUse !== undefined) {
options.allowDiskUse = crudServiceOptions.allowDiskUse
}
return options
}
class CrudService {
constructor(mongoCollection, stateOnInsert, defaultSorting, options = {}) {
assert(STATES_FINITE_STATE_MACHINE[stateOnInsert], 'Invalid `stateOnInsert`')
/**
* @type {import('mongodb').Collection} collection used by this CRUD instance
*/
this._mongoCollection = mongoCollection
this._stateOnInsert = stateOnInsert
this._defaultSorting = defaultSorting
this._options = options
}
findAll(context, query, projection, sort, skip, limit, _states, isTextSearchQuery) {
const stateQuery = getStateQuery(_states)
const isQueryValid = query && Object.keys(query).length > 0
if (isTextSearchQuery) {
addTextScoreProjection(projection)
}
const sortConfig = getSorting({
defaultSorting: this._defaultSorting, sort, isTextSearchQuery,
})
const searchQuery = isQueryValid ? { $and: [query, stateQuery] } : stateQuery
const options = getQueryOptions(this._options)
context.log.debug({ query: searchQuery, projection, sort: sortConfig, skip, limit, options }, 'findAll operation requested')
let cursor = this._mongoCollection
.find(searchQuery, options)
.project(projection)
if (sortConfig !== undefined && sortConfig !== null) { cursor = cursor.sort(sortConfig) }
if (skip !== undefined && skip !== null) { cursor = cursor.skip(skip) }
if (limit !== undefined && limit !== null) { cursor = cursor.limit(limit) }
return cursor
}
findById(context, id, query, projection, _states) {
const stateQuery = getStateQuery(_states)
const isQueryValid = query && Object.keys(query).length > 0
const searchQuery = isQueryValid
? { $and: [query, { _id: id }, stateQuery] }
: { $and: [{ _id: id }, stateQuery] }
const options = getQueryOptions(this._options)
context.log.debug({ query: searchQuery, projection, options }, 'findById operation requested')
return this._mongoCollection.findOne(searchQuery, {
projection, ...options,
})
}
aggregate(context, query, projection, sort, skip, limit, _states, isTextSearchQuery) {
const stateQuery = getStateQuery(_states)
const isQueryValid = query && Object.keys(query).length > 0
const sortConfig = getSorting({ defaultSorting: this._defaultSorting, sort, isTextSearchQuery })
let textSearchQuery = {}
if (isTextSearchQuery) {
const [path] = JSONPath({ json: query, resultType: 'pointer', path: '$..[?(@property === "$text")]' }).map(getPathFromPointer)
textSearchQuery = { $text: lget(query, path) }
lunset(query, path)
addTextScoreProjection(projection)
}
const searchQuery = isQueryValid ? { $and: [query, stateQuery] } : stateQuery
const options = getQueryOptions(this._options)
context.log.debug({ query: searchQuery, projection, sort: sortConfig, skip, limit, options }, 'aggregate operation requested')
const pipeline = [
{ $match: { ...textSearchQuery, ...stateQuery } },
{ $project: projection },
{ $match: query },
]
if (sortConfig !== undefined && sortConfig !== null) { pipeline.push({ $sort: sortConfig }) }
if (skip !== undefined && skip !== null) { pipeline.push({ $skip: Number(skip) }) }
if (limit !== undefined && limit !== null) { pipeline.push({ $limit: Number(limit) }) }
const cursor = this._mongoCollection.aggregate(pipeline)
return cursor
}
async insertOne(context, doc) {
context.log.debug({ doc }, 'insertOne operation requested')
assertDocHasNotStandardField(doc)
doc[CREATORID] = context.userId
doc[UPDATERID] = context.userId
doc[UPDATEDAT] = context.now
doc[CREATEDAT] = context.now
doc[__STATE__] = doc[__STATE__] || this._stateOnInsert
const writeOpResult = await this._mongoCollection.insertOne(doc)
context.log.debug({ docId: writeOpResult.insertedId }, 'insertOne operation executed')
return {
_id: writeOpResult.insertedId,
...doc,
}
}
async insertOneWithId(context, id, doc) {
context.log.debug({ doc }, 'insertOneWithId operation requested')
assert.ok(!doc._id, 'doc._id already exists')
assertDocHasNotStandardField(doc)
doc._id = id
doc[CREATORID] = context.userId
doc[UPDATERID] = context.userId
doc[UPDATEDAT] = context.now
doc[CREATEDAT] = context.now
doc[__STATE__] = doc[__STATE__] || this._stateOnInsert
await this._mongoCollection.insertOne(doc)
context.log.debug({ docId: id }, 'insertOneWithId operation executed')
return doc
}
/**
* performs a insert many operation over a CRUD resource
* @param {unknown} context context of http handler
* @param {unknown[]} docs array of documents
* @param {import('./QueryParser')} queryParser QueryParser instance
* @param {{ idOnly: boolean}?} opts
* @returns {Promise<unknown[] | import('mongodb').ObjectId[]>} if flag idOnly is set to true,
* returns just the mongodb object ids
*/
async insertMany(context, docs, queryParser, opts = {}) {
const { idOnly } = opts
context.log.debug({ docs }, 'insertMany operation requested')
assert(docs.length > 0, 'At least one element is required')
for (const doc of docs) {
queryParser.parseAndCastBody(doc)
assertDocHasNotStandardField(doc)
doc[CREATORID] = context.userId
doc[UPDATERID] = context.userId
doc[UPDATEDAT] = context.now
doc[CREATEDAT] = context.now
doc[__STATE__] = doc[__STATE__] || this._stateOnInsert
}
const writeOpResult = await this._mongoCollection.insertMany(docs)
context.log.debug({ docIds: writeOpResult.insertedIds }, 'insertMany operation executed')
if (!idOnly) {
for (const indexKey of Object.keys(writeOpResult.insertedIds)) {
docs[indexKey] = {
_id: writeOpResult.insertedIds[indexKey],
...docs[indexKey],
}
}
return docs
}
return Object.values(writeOpResult.insertedIds).map((_id) => ({ _id }))
}
async deleteById(context, id, query, _states) {
const stateQuery = getStateQuery(_states)
const isQueryValid = query && Object.keys(query).length > 0
const searchQuery = isQueryValid
? { $and: [query, { _id: id }, stateQuery] }
: { $and: [{ _id: id }, stateQuery] }
context.log.debug({ query: searchQuery }, 'deleteById operation requested')
const writeOpResult = await this._mongoCollection.findOneAndDelete(searchQuery)
context.log.debug({ docId: writeOpResult?._id || NO_DOCUMENT_FOUND }, 'deleteById operation executed')
return writeOpResult
}
async patchById(context, id, commands, query, projection, _states) {
const stateQuery = getStateQuery(_states)
const isQueryValid = query && Object.keys(query).length > 0
const searchQuery = isQueryValid
? { $and: [query, { _id: id }, stateQuery] }
: { $and: [{ _id: id }, stateQuery] }
context.log.debug({ query: searchQuery, commands, projection }, 'patchById operation requested')
assertCommands(commands)
commands.$set = commands.$set || {}
commands.$set[UPDATERID] = context.userId
commands.$set[UPDATEDAT] = context.now
const writeOpResult = await this._mongoCollection.findOneAndUpdate(
searchQuery,
commands,
{
returnDocument: 'after',
projection,
}
)
context.log.debug({ docId: writeOpResult?._id || NO_DOCUMENT_FOUND }, 'patchById operation executed')
return writeOpResult
}
async patchMany(context, commands, query, _states) {
const stateQuery = getStateQuery(_states)
const isQueryValid = query && Object.keys(query).length > 0
const searchQuery = isQueryValid ? { $and: [query, stateQuery] } : stateQuery
context.log.debug({ query: searchQuery, commands }, 'patchMany operation requested')
assertCommands(commands)
commands.$set = commands.$set || {}
commands.$set[UPDATERID] = context.userId
commands.$set[UPDATEDAT] = context.now
const { matchedCount, modifiedCount } = await this._mongoCollection.updateMany(searchQuery, commands)
context.log.debug({ matchedCount, modifiedCount }, 'patchMany operation executed')
return modifiedCount
}
async upsertOne(context, commands, query, projection, _states) {
const stateQuery = getStateQuery(_states)
const isQueryValid = query && Object.keys(query).length > 0
const searchQuery = isQueryValid ? { $and: [query, stateQuery] } : stateQuery
context.log.debug({ query: searchQuery, commands, projection }, 'upsertOne operation requested')
assertCommands(commands)
commands.$set = commands.$set || {}
commands.$set[UPDATERID] = context.userId
commands.$set[UPDATEDAT] = context.now
commands.$setOnInsert = commands.$setOnInsert || {}
commands.$setOnInsert[CREATORID] = context.userId
commands.$setOnInsert[CREATEDAT] = context.now
commands.$setOnInsert[__STATE__] = this._stateOnInsert
const writeOpResult = await this._mongoCollection.findOneAndUpdate(
searchQuery,
commands,
{
returnDocument: 'after',
upsert: true,
projection,
}
)
context.log.debug({ docId: writeOpResult._id }, 'upsertOne operation executed')
return writeOpResult
}
async upsertMany(context, documents, queryParser) {
context.log.debug(documents, 'upsertMany operation requested')
assert(documents.length > 0, 'At least one element is required')
const operations = []
for (const document of documents) {
queryParser.parseAndCastBody(document)
assertDocHasNotStandardField(document)
const operation = {
updateOne: {
filter: document._id ? { _id: document._id } : document,
update: {
$set: {
...document,
[UPDATERID]: context.userId,
[UPDATEDAT]: context.now,
[__STATE__]: document[__STATE__] || this._stateOnInsert,
},
$setOnInsert: {
[CREATORID]: document[CREATORID] || context.userId,
[CREATEDAT]: document[CREATEDAT] || context.now,
},
},
upsert: true,
},
}
operations.push(operation)
}
const { ok, modifiedCount, upsertedCount } = await this._mongoCollection.bulkWrite(operations)
if (!ok) { throw new Error('upsertMany failed') }
context.log.debug({ ok, modifiedCount, upsertedCount }, 'upsertMany operation executed')
return upsertedCount
}
/**
* Performs a patch bulk operation over the CRUD resource
* @param {unknown} context
* @param {unknown[]} filterUpdateCommands list of commands that needs to be executed
* @param {import('./QueryParser')} queryParser
* @param {Function} castCollectionId function that casts _id field (if defined in commands)
* @param {*} editableFields
* @param {*} aclRows
* @returns {Promise<number>} the number of modified documents
*/
// eslint-disable-next-line max-statements
async patchBulk(
context, filterUpdateCommands, queryParser, castCollectionId, editableFields, aclRows
) {
context.log.debug(filterUpdateCommands, 'patchBulk operation requested')
assert(filterUpdateCommands.length > 0, 'At least one element is required')
const unorderedBulkOp = this._mongoCollection.initializeUnorderedBulkOp()
const parsedAndCastedCommands = new Array(filterUpdateCommands.length)
for (let i = 0; i < filterUpdateCommands.length; i++) {
const { filter, update } = filterUpdateCommands[i]
const {
_id,
[QUERY]: clientQueryString,
[STATE]: state,
...otherParams
} = filter
const commands = update
const mongoQuery = resolveMongoQuery(queryParser, clientQueryString, aclRows, otherParams, false)
queryParser.parseAndCastCommands(commands, editableFields)
const allowedStates = state.split(',')
parsedAndCastedCommands[i] = {
commands,
state: allowedStates,
query: mongoQuery,
}
const stateQuery = getStateQuery(allowedStates)
const isQueryValid = mongoQuery && Object.keys(mongoQuery).length > 0
const searchQuery = isQueryValid ? { $and: [mongoQuery, stateQuery] } : { $and: [stateQuery] }
if (_id) {
searchQuery.$and.push({ _id: castCollectionId(_id) })
}
assertCommands(commands)
commands.$set = commands.$set || {}
commands.$set.updaterId = context.userId
commands.$set.updatedAt = context.now
unorderedBulkOp.find(searchQuery).updateOne(commands)
}
const { ok, modifiedCount } = await unorderedBulkOp.execute()
if (!ok) { throw new Error('patchBulk failed') }
context.log.debug({ ok, modifiedCount }, 'patchBulk operation executed')
return modifiedCount
}
async count(context, query, _states) {
const stateQuery = getStateQuery(_states)
const isQueryValid = query && Object.keys(query).length > 0
const searchQuery = isQueryValid ? { $and: [query, stateQuery] } : stateQuery
const options = getQueryOptions(this._options)
context.log.debug({ query: searchQuery, options }, 'count operation requested')
return this._mongoCollection.countDocuments(searchQuery, options)
}
async estimatedDocumentCount(context) {
context.log.debug({}, 'estimatedDocumentCount operation requested')
return this._mongoCollection.estimatedDocumentCount()
}
async deleteAll(context, query, _states) {
const stateQuery = getStateQuery(_states)
const isQueryValid = query && Object.keys(query).length > 0
const searchQuery = isQueryValid ? { $and: [query, stateQuery] } : stateQuery
context.log.debug({ query: searchQuery }, 'deleteAll operation requested')
const writeOpResult = await this._mongoCollection.deleteMany(searchQuery)
context.log.debug({ docNumber: writeOpResult.deletedCount }, 'deleteAll operation executed')
return writeOpResult.deletedCount
}
async changeStateById(context, id, stateTo, query) {
context.log.debug({ query, stateTo }, 'changeStateById operation requested')
assert.ok(stateTo in STATES_FINITE_STATE_MACHINE, `Invalid current \`stateTo\` parameter: ${stateTo}`)
const isQueryValid = query && Object.keys(query).length > 0
const searchQuery = isQueryValid
? { $and: [query, { _id: id }] }
: { _id: id }
const documentToUpdate = await this._mongoCollection.findOne(searchQuery)
if (!documentToUpdate) {
return null
}
const currentState = documentToUpdate[__STATE__]
const allowedStates = ALLOWED_STATES_MAP[currentState]
// this check on current state existence of allows this API
// to assign a __STATE__ to documents that does not have the field
// (no current state means that any transition is valid)
if (currentState && !allowedStates.includes(stateTo)) {
context.log.debug({ _id: documentToUpdate._id, from: currentState, to: stateTo }, 'transition from states not allowed')
const error = new Error(`transition from ${currentState} to ${stateTo} not allowed.`)
error.statusCode = 400
throw error
}
const commands = {
$set: {
[__STATE__]: stateTo,
[UPDATERID]: context.userId,
[UPDATEDAT]: context.now,
},
}
// adding current document state to the search filter of the operation ensure
// that the state has not changed since the find operation executed above
const { modifiedCount } = await this._mongoCollection.updateOne(
{ $and: [searchQuery, { __STATE__: currentState }] },
commands
)
context.log.debug({ modifiedCount }, 'changeStateById operation executed')
return modifiedCount
}
async changeStateMany(context, filterUpdateCommands) {
context.log.debug({ filterUpdateCommands }, 'changeStateMany operation requested')
assert(filterUpdateCommands.length > 0, 'At least one element is required')
const unorderedBulkOp = this._mongoCollection.initializeUnorderedBulkOp()
for (let i = 0; i < filterUpdateCommands.length; i++) {
const { query, stateTo } = filterUpdateCommands[i]
const currentState = STATES_FINITE_STATE_MACHINE[stateTo]
assert(currentState, `Invalid current \`stateTo\` parameter: ${stateTo}`)
const stateQuery = { [__STATE__]: { $in: currentState } }
const isQueryValid = query && Object.keys(query).length > 0
const searchQuery = isQueryValid ? { $and: [query, stateQuery] } : stateQuery
const commands = {
$set: {
__STATE__: stateTo,
updaterId: context.userId,
updatedAt: context.now,
},
}
context.log.debug({ query: searchQuery, commands }, `changeStateMany - step #${i + 1} executed`)
unorderedBulkOp.find(searchQuery).update(commands)
}
const res = await unorderedBulkOp.execute()
const { ok, modifiedCount } = res
if (!ok) { throw new Error('changeStateMany failed') }
context.log.debug({ ok, modifiedCount }, 'changeStateMany operation executed')
return modifiedCount
}
}
function addTextScoreProjection(projection) {
if (!Object.keys(projection).includes('score')) {
projection.score = textScore
}
}
function getSorting({ defaultSorting, sort, isTextSearchQuery }) {
if (isTextSearchQuery && !sort) {
return { score: textScore }
}
if (defaultSorting && !sort) {
return defaultSorting
}
return sort
}
function assertDocHasNotStandardField(doc) {
STANDARD_FIELDS.forEach(field => {
assert.ok(!doc[field], `${field} cannot be specified`)
})
}
function assertCommands(command) {
if (command.$set) {
assertDocHasNotStandardField(command.$set)
}
if (command.$inc) {
assertDocHasNotStandardField(command.$inc)
}
if (command.$mul) {
assertDocHasNotStandardField(command.$mul)
}
if (command.$currentDate) {
assertDocHasNotStandardField(command.$currentDate)
}
if (command.$setOnInsert) {
assertDocHasNotStandardField(command.$setOnInsert)
}
if (command.$unset) {
assertDocHasNotStandardField(command.$unset)
}
if (command.$push) {
assertDocHasNotStandardField(command.$push)
}
if (command.$addToSet) {
assertDocHasNotStandardField(command.$addToSet)
}
if (command.$pull) {
assertDocHasNotStandardField(command.$pull)
}
for (const key of Object.keys(command)) {
if (!ALLOWED_COMMANDS.includes(key)) {
assert.fail(`Unknown operator: ${key}`)
}
}
}
CrudService.STANDARD_FIELDS = STANDARD_FIELDS
module.exports = CrudService