@natlibfi/melinda-rest-api-commons 4.2.4-alpha.5 → 4.2.4-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mongo.js CHANGED
@@ -13,6 +13,7 @@ var _utils = require("./utils.js");
13
13
  var _moment = _interopRequireDefault(require("moment"));
14
14
  var _httpStatus = _interopRequireDefault(require("http-status"));
15
15
  var _mongoSanitize = _interopRequireDefault(require("mongo-sanitize"));
16
+ var _debug = _interopRequireDefault(require("debug"));
16
17
  /* eslint-disable max-lines */
17
18
 
18
19
  //import isDeepStrictEqual from 'util';
@@ -46,15 +47,45 @@ var _mongoSanitize = _interopRequireDefault(require("mongo-sanitize"));
46
47
  }
47
48
  */
48
49
 
49
- async function _default(MONGO_URI, collection) {
50
+ async function _default(MONGO_URI, collection, db = 'rest-api', test = false) {
50
51
  const logger = (0, _melindaBackendCommons.createLogger)();
52
+ const debug = (0, _debug.default)('@natlibfi/melinda-rest-api-commons/mongo');
53
+ const debugDev = debug.extend(':dev');
51
54
 
52
55
  // Connect to mongo (MONGO)
53
56
  const client = await _mongodb.MongoClient.connect(MONGO_URI);
54
- const db = client.db('rest-api');
55
- const gridFSBucket = new _mongodb.GridFSBucket(db, {
57
+ const dbConnection = client.db(db);
58
+ const gridFSBucket = new _mongodb.GridFSBucket(dbConnection, {
56
59
  bucketName: collection
57
60
  });
61
+ const operator = dbConnection.collection(collection);
62
+ debugDev(`mongo: ${MONGO_URI}, db: ${db}, collection: ${collection}, test: ${test}`);
63
+ if (test) {
64
+ // return also internal functions if testing
65
+ return {
66
+ createPrio,
67
+ createBulk,
68
+ checkAndSetState,
69
+ checkAndSetImportJobState,
70
+ query,
71
+ createProjection,
72
+ queryById,
73
+ checkTimeOut,
74
+ remove,
75
+ readContent,
76
+ removeContent,
77
+ getOne,
78
+ getStream,
79
+ setState,
80
+ setImportJobState,
81
+ pushIds,
82
+ pushMessages,
83
+ setOperation,
84
+ setOperations,
85
+ addBlobSize,
86
+ setBlobSize
87
+ };
88
+ }
58
89
  return {
59
90
  createPrio,
60
91
  createBulk,
@@ -83,6 +114,7 @@ async function _default(MONGO_URI, collection) {
83
114
  operation,
84
115
  operationSettings
85
116
  }) {
117
+ debugDev('createPrio');
86
118
  const time = (0, _moment.default)().toDate();
87
119
  const newQueueItem = {
88
120
  correlationId,
@@ -108,13 +140,17 @@ async function _default(MONGO_URI, collection) {
108
140
  modificationTime: time
109
141
  };
110
142
  try {
111
- const result = await db.collection(collection).insertOne(newQueueItem);
143
+ debugDev(`Inserting: ${JSON.stringify(newQueueItem)} to ${collection}}`);
144
+ const result = await operator.insertOne(newQueueItem);
145
+ debugDev(JSON.stringify(result));
112
146
  if (result.acknowledged) {
113
147
  logger.info(`New PRIO queue item for ${operation} ${correlationId} has been made in ${collection}`);
114
148
  return;
115
149
  }
150
+ // TEST-COVERAGE: this error is not (currently) tested
116
151
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR);
117
152
  } catch (error) {
153
+ // TEST-COVERAGE: this error is not (currently) tested
118
154
  const errorMessage = error.payload || error.message || '';
119
155
  (0, _utils.logError)(error);
120
156
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, `Mongo errored: ${errorMessage}`);
@@ -161,16 +197,17 @@ async function _default(MONGO_URI, collection) {
161
197
 
162
198
  // eslint-disable-next-line functional/no-conditional-statements
163
199
  if (stream) {
200
+ debug(`Creating streamBulk`);
164
201
  try {
165
- // No await here, promises later
166
- db.collection(collection).insertOne(newQueueItem);
167
- logger.info(`New BULK queue item for ${operation} ${correlationId} has been made in ${collection}!`);
168
- return new Promise((resolve, reject) => {
202
+ await new Promise((resolve, reject) => {
169
203
  const outputStream = gridFSBucket.openUploadStream(correlationId);
170
204
  stream.on('error', reject).on('data', chunk => outputStream.write(chunk)).on('end', () => outputStream.end(undefined, undefined, () => {
171
205
  resolve(correlationId);
172
206
  }));
173
207
  });
208
+ logger.info(`New BULK queue item for ${operation} ${correlationId} has been made in ${collection}!`);
209
+ debug(`New BULK queue item for ${operation} ${correlationId} has been made in ${collection}!`);
210
+ return operator.insertOne(newQueueItem);
174
211
  } catch (error) {
175
212
  const errorMessage = error.payload || error.message || '';
176
213
  (0, _utils.logError)(error);
@@ -178,19 +215,23 @@ async function _default(MONGO_URI, collection) {
178
215
  }
179
216
  }
180
217
  logger.debug(`No stream`);
218
+ debug(`Creating noStreamBulk`);
181
219
  // eslint-disable-next-line functional/no-conditional-statements
182
220
  if (!stream) {
183
221
  try {
184
- const result = await db.collection(collection).insertOne(newQueueItem);
222
+ const result = await operator.insertOne(newQueueItem);
185
223
  if (result.acknowledged) {
186
224
  logger.info(`New noStream BULK queue item for ${operation} ${correlationId} has been made in ${collection}`);
225
+ debug(`New noStream BULK queue item for ${operation} ${correlationId} has been made in ${collection}`);
187
226
  return {
188
227
  correlationId,
189
228
  queueItemState: _constants.QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS
190
229
  };
191
230
  }
231
+ // TEST-COVERAGE: this error is not (currently) tested
192
232
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR);
193
233
  } catch (error) {
234
+ // TEST-COVERAGE: this error is not (currently) tested
194
235
  const errorMessage = error.payload || error.message || '';
195
236
  (0, _utils.logError)(error);
196
237
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, `Mongo errored: ${errorMessage}`);
@@ -199,14 +240,15 @@ async function _default(MONGO_URI, collection) {
199
240
  }
200
241
 
201
242
  // Check state that the queueItem has not waited too long and set state
243
+ // Optionally set also queueItems errorStatus & errorMessage
202
244
  async function checkAndSetState({
203
245
  correlationId,
204
246
  state,
205
247
  errorMessage = undefined,
206
248
  errorStatus = undefined
207
249
  }) {
208
- // checkTimeOut returns true, if queueItem is fresher than 1 minute and it's state is not ABORT/ERROR
209
- // otherwise it sets queueItem to state ABORT (408, 'Timeout')
250
+ // checkTimeOut returns true, if queueItem is fresher than 1 minute and it's state is not ABORT/ERROR/DONE
251
+ // otherwise it sets queueItem and importJobStates to state ABORT and add errorStatus and errorMessage (408, 'Timeout')
210
252
  const timeOut = await checkTimeOut({
211
253
  correlationId
212
254
  });
@@ -221,16 +263,15 @@ async function _default(MONGO_URI, collection) {
221
263
  return false;
222
264
  }
223
265
 
224
- // Check state that the queueItem has not waited too long and set state
266
+ // Check state that the queueItem has not waited too long and set importJobState
267
+ // Note: checkAndSetImportJobState cannot be used to set queueItems errorStatus & errorMessage (expect in case of a TimeOut)
225
268
  async function checkAndSetImportJobState({
226
269
  correlationId,
227
270
  operation,
228
- importJobState,
229
- errorMessage = '',
230
- errorStatus = ''
271
+ importJobState
231
272
  }) {
232
- // checkTimeOut returns true, if queueItem is fresher than 1 minute and it's state is not ABORT/ERROR
233
- // otherwise it sets queueItem to state ABORT (408, 'Timeout')
273
+ // checkTimeOut returns true, if queueItem is fresher than 1 minute and it's state is not ABORT/ERROR/DONE
274
+ // otherwise it sets queueItem and importJobStates to state ABORT and errorStatue and errorMessage (408, 'Timeout')
234
275
  logger.debug(`${correlationId}, ${importJobState}, ${operation}`);
235
276
  const timeOut = await checkTimeOut({
236
277
  correlationId,
@@ -241,25 +282,25 @@ async function _default(MONGO_URI, collection) {
241
282
  return setImportJobState({
242
283
  correlationId,
243
284
  operation,
244
- importJobState,
245
- errorMessage,
246
- errorStatus
285
+ importJobState
247
286
  });
248
287
  }
249
288
  return false;
250
289
  }
251
290
  async function query(params, showParams = {}) {
252
291
  logger.debug(`Querying: ${JSON.stringify(params)}, ${JSON.stringify(showParams)}`);
292
+ debug(`Querying: ${JSON.stringify(params)}, ${JSON.stringify(showParams)}`);
253
293
  const {
254
294
  limit = 1000,
255
295
  skip = 0,
256
296
  ...rest
257
297
  } = params;
258
- const result = await db.collection(collection).find(rest, {
298
+ const result = await operator.find(rest, {
259
299
  projection: createProjection(showParams)
260
300
  }).limit(parseInt(limit, 10)).skip(parseInt(skip, 10)).toArray();
261
301
  logger.debug(`Query result: ${result.length > 0 ? 'Found!' : 'Not found!'}`);
262
302
  logger.silly(`${JSON.stringify(result)}`);
303
+ debug(`${JSON.stringify(result)}`);
263
304
  return result;
264
305
  }
265
306
 
@@ -269,6 +310,7 @@ async function _default(MONGO_URI, collection) {
269
310
 
270
311
  function createProjection(showParams = {}) {
271
312
  logger.silly(`Creating projection for query: ${JSON.stringify(showParams)}`);
313
+ debug(`Creating projection for query: ${JSON.stringify(showParams)}`);
272
314
  const {
273
315
  showAll = 0,
274
316
  showOperations = 0,
@@ -276,8 +318,18 @@ async function _default(MONGO_URI, collection) {
276
318
  showRecordLoadParams = 0,
277
319
  showImportJobState = 0
278
320
  } = showParams;
321
+ const combinedShowParams = {
322
+ showAll,
323
+ showOperations,
324
+ showOperationSettings,
325
+ showRecordLoadParams,
326
+ showImportJobState
327
+ };
279
328
  logger.debug(`showAll: ${showAll}, showOperations: ${showOperations}, showOperationSettings: ${showOperationSettings}, showRecordLoadParams: ${showRecordLoadParams}, showImportJobState: ${showImportJobState}`);
280
- if (showAll) {
329
+ debug(`showAll: ${showAll}, showOperations: ${showOperations}, showOperationSettings: ${showOperationSettings}, showRecordLoadParams: ${showRecordLoadParams}, showImportJobState: ${showImportJobState}`);
330
+ debug(`${JSON.stringify(combinedShowParams)}`);
331
+ if (showAll === true || showAll === '1' || showAll === 1) {
332
+ debug(`ShowAll: ${showAll}`);
281
333
  return {
282
334
  _id: 0
283
335
  };
@@ -288,57 +340,65 @@ async function _default(MONGO_URI, collection) {
288
340
  'showRecordLoadParams': 'recordLoadParams',
289
341
  'showImportJobState': 'importJobState'
290
342
  };
291
- const result = Object.keys(showParams).filter(param => param !== 'showAll' && showParams[param] !== true && showParams[param] !== 1).filter(param => showParamToField[param]).map(param => showParamToField[param]);
343
+ const result = Object.keys(combinedShowParams).filter(param => param !== 'showAll' && combinedShowParams[param] !== true && combinedShowParams[param] !== 1 && combinedShowParams[param] !== '1').filter(param => showParamToField[param]).map(param => showParamToField[param]);
292
344
  logger.silly(`We want to exclude from projection: ${JSON.stringify(result)}`);
345
+ debug(`We want to exclude from projection: ${JSON.stringify(result)}`);
293
346
  const excludeObject = Object.fromEntries(result.map(param => [param, 0]));
294
347
  logger.silly(`We want to exclude from projection: ${JSON.stringify(excludeObject)}`);
348
+ debug(`We want to exclude from projection: ${JSON.stringify(excludeObject)}`);
295
349
  return {
296
350
  _id: 0,
297
351
  ...excludeObject
298
352
  };
299
353
  }
354
+
355
+ // Note: edited in v4.2.4 to return queueItem *after* possible timout has aborted it
356
+ // Note: previous versions returned queueItem *before* its state/queueItemState is timeOuted
300
357
  async function queryById({
301
358
  correlationId,
302
359
  checkModTime = false
303
360
  }) {
304
- const result = await db.collection(collection).findOne({
305
- correlationId
306
- });
307
361
  if (checkModTime) {
308
- const timeOut = await checkTimeOut({
362
+ debug(`queryById checkModTime: ${checkModTime}`);
363
+ await checkTimeOut({
364
+ correlationId
365
+ });
366
+ return queryById({
309
367
  correlationId
310
368
  });
311
- if (timeOut) {
312
- return queryById({
313
- correlationId
314
- });
315
- }
316
- return result;
317
369
  }
370
+ const result = await operator.findOne({
371
+ correlationId
372
+ }, {
373
+ projection: {
374
+ _id: 0
375
+ }
376
+ });
318
377
  return result;
319
378
  }
320
379
 
321
380
  // Check that if the item has waited too long
322
381
  // If the last modification time for the queueItem is older than 1 minute
323
382
  // set state to ABORT and return false, otherwise return true
324
- // If the state is already ABORT or ERROR return false
383
+ // If the state is already ABORT or ERROR or DONE return false
325
384
 
326
385
  async function checkTimeOut({
327
386
  correlationId
328
387
  }) {
329
388
  const {
330
389
  modificationTime,
331
- queueitemState: oldState,
390
+ queueItemState: oldState,
332
391
  importJobState
333
- } = await db.collection(collection).findOne({
392
+ } = await operator.findOne({
334
393
  correlationId
335
394
  });
336
-
395
+ //debug(`${modificationTime} - oldState: ${oldState}`);
337
396
  // should we check for DONE too?
338
397
  if ([_constants.QUEUE_ITEM_STATE.ABORT, _constants.QUEUE_ITEM_STATE.ERROR, _constants.QUEUE_ITEM_STATE.DONE].includes(oldState)) {
339
398
  logger.silly(`${correlationId} has already state: ${oldState}`);
340
399
  return false;
341
400
  }
401
+ debug(`test: ${test}`);
342
402
  const timeoutTime = (0, _moment.default)(modificationTime).add(1, 'm');
343
403
  logger.silly(`${correlationId} timeOut @ ${timeoutTime}`);
344
404
  if (timeoutTime.isBefore()) {
@@ -377,26 +437,36 @@ async function _default(MONGO_URI, collection) {
377
437
  }
378
438
  return true;
379
439
  }
440
+
441
+ // eslint-disable-next-line max-statements
380
442
  async function remove(params) {
381
443
  logger.silly(`${JSON.stringify(params)}`);
382
444
  logger.info(`Removing from Mongo (${collection}) id: ${params.correlationId}`);
445
+ debug(`${JSON.stringify(params)}`);
446
+ debug(`Removing from Mongo (${collection}) id: ${params.correlationId}`);
383
447
  const clean = (0, _mongoSanitize.default)(params.correlationId);
384
448
  logger.silly(`mongo/remove: clean: ${JSON.stringify(clean)}`);
449
+ debug(`mongo/remove: clean: ${JSON.stringify(clean)}`);
385
450
  try {
386
451
  //const metadataResult = await getFileMetadata({filename: clean});
387
452
  //logger.debug(`mongo/remove: metadataResult: ${JSON.stringify(metadataResult)}`);
388
- const noContent = await removeContent(params);
453
+ const noContent = await removeContent(params.correlationId);
454
+ debug(`noContent (removeContent result): ${JSON.stringify(noContent)}`);
389
455
  if (noContent) {
390
- await db.collection(collection).deleteOne({
456
+ const deleteResult = await operator.deleteOne({
391
457
  correlationId: clean
392
458
  });
459
+ debug(`deleteResult: ${JSON.stringify(deleteResult)}`);
393
460
  return true;
394
461
  }
395
462
  } catch (err) {
463
+ // TEST-COVERAGE: this error is not (currently) tested
396
464
  if (err instanceof _mongodb.MongoDriverError) {
465
+ debug();
397
466
  if (err.message.indexOf('File not found for id') !== -1) {
398
467
  logger.silly(`mongo/remove: File not found, removing queueItem ${JSON.stringify(clean)} from ${collection}`);
399
- await db.collection(collection).deleteOne({
468
+ debug(`mongo/remove: File not found, removing queueItem ${JSON.stringify(clean)} from ${collection}`);
469
+ await operator.deleteOne({
400
470
  correlationId: clean
401
471
  });
402
472
  return true;
@@ -409,11 +479,13 @@ async function _default(MONGO_URI, collection) {
409
479
  }
410
480
  async function readContent(correlationId) {
411
481
  logger.info(`Reading content from mongo for id: ${correlationId} in ${collection}`);
482
+ debug(`Reading content from mongo for id: ${correlationId} in ${collection}`);
412
483
  const clean = (0, _mongoSanitize.default)(correlationId);
413
- const result = await db.collection(collection).findOne({
484
+ debug(clean);
485
+ const result = await operator.findOne({
414
486
  correlationId: clean
415
487
  }); // njsscan-ignore: node_nosqli_injection
416
-
488
+ debug(result);
417
489
  if (result) {
418
490
  const {
419
491
  operationSettings
@@ -425,6 +497,8 @@ async function _default(MONGO_URI, collection) {
425
497
  };
426
498
  }
427
499
  logger.debug(`OperationSettings for ${correlationId}: ${JSON.stringify(operationSettings)}`);
500
+ debug(`OperationSettings for ${correlationId}: ${JSON.stringify(operationSettings)}`);
501
+ debug(`Content is only available for streamBulk jobs. ${correlationId} is not a streamBulk job.`);
428
502
  throw new _melindaCommons.Error(_httpStatus.default.BAD_REQUEST, {
429
503
  message: `Content is only available for streamBulk jobs. ${correlationId} is not a streamBulk job.`
430
504
  });
@@ -436,50 +510,59 @@ async function _default(MONGO_URI, collection) {
436
510
  async function removeContent(params) {
437
511
  logger.info(`Removing content from mongo for id: ${params.correlationId} in ${collection}`);
438
512
  const clean = (0, _mongoSanitize.default)(params.correlationId);
439
- const result = await db.collection(collection).findOne({
513
+ const result = await operator.findOne({
440
514
  correlationId: clean
441
515
  }); // njsscan-ignore: node_nosqli_injection
442
516
  logger.silly(`mongo/removeContent: result ${JSON.stringify(result)}`);
443
517
  if (result) {
518
+ // TEST-COVERAGE: next two lines are not (currently) tested
444
519
  await gridFSBucket.delete(clean);
445
520
  return true;
446
521
  }
447
522
  return true;
448
523
  }
449
-
450
- // eslint-disable-next-line max-statements
451
524
  function getOne({
452
525
  queueItemState,
453
526
  importJobState = undefined
454
527
  }) {
528
+ //params example: "queueItemState": "IMPORTER.IN_QUEUE", "importJobState":{"importJobState.UPDATE": "IN_QUEUE"}
455
529
  logger.silly(`queueItemState: ${queueItemState}, importJobState: ${JSON.stringify(importJobState)}`);
530
+ //debug(`queueItemState: ${queueItemState}, importJobState: ${JSON.stringify(importJobState)}`);
456
531
  const cleanQueueItemState = queueItemState ? {
457
532
  queueItemState: (0, _mongoSanitize.default)(queueItemState)
458
533
  } : undefined;
534
+ const options = {
535
+ projection: {
536
+ _id: 0
537
+ }
538
+ };
459
539
  try {
460
540
  // Just queueItemState
461
541
  if (queueItemState && importJobState === undefined) {
462
542
  logger.silly(`Checking DB ${collection} for just ${JSON.stringify(cleanQueueItemState.queueItemState)}`);
463
- return db.collection(collection).findOne({
543
+ //debug(`Checking DB ${collection} for just ${JSON.stringify(cleanQueueItemState.queueItemState)}`);
544
+ return operator.findOne({
464
545
  ...cleanQueueItemState
465
- });
546
+ }, options);
466
547
  }
467
548
 
468
549
  // importJobState
469
550
  if (importJobState && queueItemState === undefined) {
470
551
  logger.silly(`Checking DB ${collection} for ${JSON.stringify(importJobState)}`);
471
- return db.collection(collection).findOne({
552
+ //debug(`Checking DB ${collection} for ${JSON.stringify(importJobState)}`);
553
+ return operator.findOne({
472
554
  ...importJobState
473
- });
555
+ }, options);
474
556
  }
475
557
 
476
558
  // importJobState and queueItemState
477
559
  if (importJobState && queueItemState) {
478
560
  logger.silly(`Checking DB ${collection} for ${queueItemState} and ${JSON.stringify(importJobState)}`);
479
- return db.collection(collection).findOne({
561
+ //debug(`Checking DB ${collection} for ${queueItemState} and ${JSON.stringify(importJobState)}`);
562
+ return operator.findOne({
480
563
  ...cleanQueueItemState,
481
564
  ...importJobState
482
- });
565
+ }, options);
483
566
  }
484
567
  logger.debug(`getOne not working!`);
485
568
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, 'Missing parameters, cannot get queueItem');
@@ -496,6 +579,7 @@ async function _default(MONGO_URI, collection) {
496
579
  // Return content stream
497
580
  return gridFSBucket.openDownloadStreamByName(clean);
498
581
  } catch (error) {
582
+ // TEST-COVERAGE: this error is not (currently) tested
499
583
  const errorMessage = error.payload || error.message || '';
500
584
  (0, _utils.logError)(error);
501
585
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, `Mongo errored: ${errorMessage}`);
@@ -509,7 +593,7 @@ async function _default(MONGO_URI, collection) {
509
593
  logger.verbose(`Push ids (${handledIds.length}) and rejectedIds (${rejectedIds.length}) ${correlationId} to ${collection}`);
510
594
  logger.debug(`ids (${handledIds.length}): ${JSON.stringify(handledIds)}, rejectedIds ${rejectedIds.length}: ${JSON.stringify(rejectedIds)}`);
511
595
  const clean = (0, _mongoSanitize.default)(correlationId);
512
- await db.collection(collection).updateOne({
596
+ await operator.updateOne({
513
597
  correlationId: clean
514
598
  }, {
515
599
  $set: {
@@ -534,7 +618,8 @@ async function _default(MONGO_URI, collection) {
534
618
  logger.silly(`Messages (${messages.length}): ${JSON.stringify(messages)}}`);
535
619
  const clean = (0, _mongoSanitize.default)(correlationId);
536
620
  const cleanMessageField = (0, _mongoSanitize.default)(messageField);
537
- await db.collection(collection).updateOne({
621
+ debug(`${messageField} -> ${cleanMessageField}`);
622
+ await operator.updateOne({
538
623
  correlationId: clean
539
624
  }, {
540
625
  $set: {
@@ -559,6 +644,7 @@ async function _default(MONGO_URI, collection) {
559
644
  const stateInQueueItemStatesValidator = Object.values(_constants.QUEUE_ITEM_STATE.VALIDATOR).indexOf(state) > -1;
560
645
  const stateInQueueItemStatesImporter = Object.values(_constants.QUEUE_ITEM_STATE.IMPORTER).indexOf(state) > -1;
561
646
  if (!stateInQueueItemStates && !stateInQueueItemStatesValidator && !stateInQueueItemStatesImporter) {
647
+ debug(`Trying to set invalid state ${state}`);
562
648
  throw new _melindaCommons.Error(_httpStatus.default.BAD_REQUEST, 'Trying to set invalid state');
563
649
  }
564
650
  const clean = (0, _mongoSanitize.default)(correlationId);
@@ -572,7 +658,7 @@ async function _default(MONGO_URI, collection) {
572
658
  // Do not update value that are undefined
573
659
  // eslint-disable-next-line functional/immutable-data
574
660
  Object.keys(updateValues).forEach(key => updateValues[key] === undefined && delete updateValues[key]);
575
- return db.collection(collection).findOneAndUpdate({
661
+ return operator.findOneAndUpdate({
576
662
  correlationId: clean
577
663
  }, {
578
664
  $set: updateValues
@@ -580,7 +666,7 @@ async function _default(MONGO_URI, collection) {
580
666
  projection: {
581
667
  _id: 0
582
668
  },
583
- returnNewDocument: true
669
+ returnDocument: 'after'
584
670
  });
585
671
  }
586
672
  function setImportJobState({
@@ -590,13 +676,16 @@ async function _default(MONGO_URI, collection) {
590
676
  }) {
591
677
  // should this also get importJobState as previously created object? {}
592
678
  logger.info(`Setting queue-item importJobState: {${operation}: ${importJobState}} for ${correlationId}`);
679
+ debug(`Setting queue-item importJobState: {${operation}: ${importJobState}} for ${correlationId}`);
593
680
  const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId);
594
681
  const cleanImportJobState = (0, _mongoSanitize.default)(importJobState);
595
682
  if (!(operation in _constants.OPERATIONS)) {
596
- throw new _melindaCommons.Error('400', 'Invalid operation for import job state');
683
+ debug(`Error: ${operation} is not in ${JSON.stringify(_constants.OPERATIONS)}`);
684
+ throw new _melindaCommons.Error(_httpStatus.default.BAD_REQUEST, 'Invalid operation for import job state');
597
685
  }
598
686
  if (!(cleanImportJobState in _constants.IMPORT_JOB_STATE)) {
599
- throw new _melindaCommons.Error('400', 'Invalid import job state');
687
+ debug(`Error: ${cleanImportJobState} is not in ${JSON.stringify(_constants.IMPORT_JOB_STATE)}`);
688
+ throw new _melindaCommons.Error(_httpStatus.default.BAD_REQUEST, 'Invalid import job state');
600
689
  }
601
690
  const newJobState = getNewJobState(operation, cleanImportJobState);
602
691
  function getNewJobState(operation, cleanImportJobState) {
@@ -615,9 +704,11 @@ async function _default(MONGO_URI, collection) {
615
704
  'importJobState.FIX': cleanImportJobState
616
705
  };
617
706
  }
707
+ // istanbul ignore next
708
+ // Ignoring for coverage - we error this already
618
709
  throw new _melindaCommons.Error('400', 'Invalid operation for import job state');
619
710
  }
620
- return db.collection(collection).findOneAndUpdate({
711
+ return operator.findOneAndUpdate({
621
712
  correlationId: cleanCorrelationId
622
713
  }, {
623
714
  $set: {
@@ -628,7 +719,7 @@ async function _default(MONGO_URI, collection) {
628
719
  projection: {
629
720
  _id: 0
630
721
  },
631
- returnNewDocument: true
722
+ returnDocument: 'after'
632
723
  });
633
724
  }
634
725
  async function setOperation({
@@ -638,13 +729,13 @@ async function _default(MONGO_URI, collection) {
638
729
  const newOperation = operation;
639
730
  const {
640
731
  operation: oldOperation
641
- } = await db.collection(collection).findOne({
732
+ } = await operator.findOne({
642
733
  correlationId
643
734
  });
644
735
  logger.info(`Setting queue-item operation from ${oldOperation} to ${newOperation} for ${correlationId} to ${collection}`);
645
736
  const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId);
646
737
  const cleanNewOperation = (0, _mongoSanitize.default)(newOperation);
647
- const result = await db.collection(collection).findOneAndUpdate({
738
+ const result = await operator.findOneAndUpdate({
648
739
  correlationId: cleanCorrelationId
649
740
  }, {
650
741
  $set: {
@@ -655,9 +746,10 @@ async function _default(MONGO_URI, collection) {
655
746
  projection: {
656
747
  _id: 0
657
748
  },
658
- returnNewDocument: true
749
+ returnDocument: 'after'
659
750
  });
660
- return result.ok;
751
+ debugDev(`${JSON.stringify(result)}`);
752
+ return result.ok || result;
661
753
  // logger.debug(JSON.stringify(result));
662
754
  }
663
755
  async function setOperations({
@@ -666,7 +758,7 @@ async function _default(MONGO_URI, collection) {
666
758
  removeOperation = undefined
667
759
  }) {
668
760
  const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId);
669
- const queueItem = await db.collection(collection).findOne({
761
+ const queueItem = await operator.findOne({
670
762
  correlationId: cleanCorrelationId
671
763
  });
672
764
  logger.silly(`We found a queueItem: ${JSON.stringify(queueItem)}`);
@@ -676,7 +768,7 @@ async function _default(MONGO_URI, collection) {
676
768
  const operationsAfterRemoveAndAdd = operationsAfterRemove.includes(addOperation) ? operationsAfterRemove : [...operationsAfterRemove, addOperation];
677
769
  logger.silly(`operationsAfterRemove: ${operationsAfterRemove}`);
678
770
  logger.silly(`operationAfterRemoveAndAdd: ${operationsAfterRemoveAndAdd}`);
679
- const result = await db.collection(collection).findOneAndUpdate({
771
+ const result = await operator.findOneAndUpdate({
680
772
  correlationId: cleanCorrelationId
681
773
  }, {
682
774
  $set: {
@@ -687,16 +779,17 @@ async function _default(MONGO_URI, collection) {
687
779
  projection: {
688
780
  _id: 0
689
781
  },
690
- returnNewDocument: true
782
+ returnDocument: 'after'
691
783
  });
692
- return result.ok;
784
+ debugDev(`${JSON.stringify(result)}`);
785
+ return result.ok || result;
693
786
  // logger.debug(JSON.stringify(result));
694
787
  }
695
788
  async function addBlobSize({
696
789
  correlationId
697
790
  }) {
698
791
  const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId);
699
- const result = await db.collection(collection).findOneAndUpdate({
792
+ const result = await operator.findOneAndUpdate({
700
793
  correlationId: cleanCorrelationId,
701
794
  queueItemState: _constants.QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS
702
795
  }, {
@@ -710,9 +803,10 @@ async function _default(MONGO_URI, collection) {
710
803
  projection: {
711
804
  _id: 0
712
805
  },
713
- returnNewDocument: true
806
+ returnDocument: 'after'
714
807
  });
715
808
  logger.verbose(`AddBlobSizeResult in mongo: ${JSON.stringify(result)}`);
809
+ debugDev(`${JSON.stringify(result)}`);
716
810
  return result;
717
811
  }
718
812
  async function setBlobSize({
@@ -721,7 +815,7 @@ async function _default(MONGO_URI, collection) {
721
815
  }) {
722
816
  const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId);
723
817
  const cleanBlobSize = (0, _mongoSanitize.default)(blobSize);
724
- const result = await db.collection(collection).findOneAndUpdate({
818
+ const result = await operator.findOneAndUpdate({
725
819
  correlationId: cleanCorrelationId
726
820
  }, {
727
821
  $set: {
@@ -732,9 +826,10 @@ async function _default(MONGO_URI, collection) {
732
826
  projection: {
733
827
  _id: 0
734
828
  },
735
- returnNewDocument: true
829
+ returnDocument: 'after'
736
830
  });
737
831
  logger.verbose(`SetBlobSizeResult in mongo: ${JSON.stringify(result)}`);
832
+ debugDev(`${JSON.stringify(result)}`);
738
833
  return result;
739
834
  }
740
835
  }