@natlibfi/melinda-rest-api-commons 2.3.2-alpha.5 → 2.3.2-alpha.7

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
@@ -4,25 +4,15 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = _default;
7
-
8
7
  var _mongodb = require("mongodb");
9
-
10
8
  var _melindaBackendCommons = require("@natlibfi/melinda-backend-commons");
11
-
12
9
  var _melindaCommons = require("@natlibfi/melinda-commons");
13
-
14
10
  var _constants = require("./constants");
15
-
16
11
  var _utils = require("./utils.js");
17
-
18
12
  var _moment = _interopRequireDefault(require("moment"));
19
-
20
13
  var _httpStatus = _interopRequireDefault(require("http-status"));
21
-
22
14
  var _mongoSanitize = _interopRequireDefault(require("mongo-sanitize"));
23
-
24
15
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
25
-
26
16
  /**
27
17
  *
28
18
  * @licstart The following is the entire license notice for the JavaScript code in this file.
@@ -50,6 +40,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
50
40
  * for the JavaScript code in this file.
51
41
  *
52
42
  */
43
+
53
44
  //import isDeepStrictEqual from 'util';
54
45
 
55
46
  /* QueueItem:
@@ -80,9 +71,11 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
80
71
  "modificationTime":"2020-01-01T00:00:01.000Z",
81
72
  }
82
73
  */
74
+
83
75
  async function _default(MONGO_URI, collection) {
84
- const logger = (0, _melindaBackendCommons.createLogger)(); // Connect to mongo (MONGO)
76
+ const logger = (0, _melindaBackendCommons.createLogger)();
85
77
 
78
+ // Connect to mongo (MONGO)
86
79
  const client = await _mongodb.MongoClient.connect(MONGO_URI, {
87
80
  useNewUrlParser: true,
88
81
  useUnifiedTopology: true
@@ -112,7 +105,6 @@ async function _default(MONGO_URI, collection) {
112
105
  addBlobSize,
113
106
  setBlobSize
114
107
  };
115
-
116
108
  async function createPrio({
117
109
  correlationId,
118
110
  cataloger,
@@ -143,22 +135,18 @@ async function _default(MONGO_URI, collection) {
143
135
  creationTime: time,
144
136
  modificationTime: time
145
137
  };
146
-
147
138
  try {
148
139
  const result = await db.collection(collection).insertOne(newQueueItem);
149
-
150
140
  if (result.acknowledged) {
151
141
  logger.info(`New PRIO queue item for ${operation} ${correlationId} has been made in ${collection}`);
152
142
  return;
153
143
  }
154
-
155
144
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR);
156
145
  } catch (error) {
157
146
  (0, _utils.logError)(error);
158
147
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR);
159
148
  }
160
149
  }
161
-
162
150
  async function createBulk({
163
151
  correlationId,
164
152
  cataloger,
@@ -193,8 +181,9 @@ async function _default(MONGO_URI, collection) {
193
181
  errorStatus: '',
194
182
  creationTime: time,
195
183
  modificationTime: time
196
- }; // eslint-disable-next-line functional/no-conditional-statement
184
+ };
197
185
 
186
+ // eslint-disable-next-line functional/no-conditional-statement
198
187
  if (stream) {
199
188
  try {
200
189
  // No await here, promises later
@@ -211,13 +200,11 @@ async function _default(MONGO_URI, collection) {
211
200
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR);
212
201
  }
213
202
  }
214
-
215
- logger.debug(`No stream`); // eslint-disable-next-line functional/no-conditional-statement
216
-
203
+ logger.debug(`No stream`);
204
+ // eslint-disable-next-line functional/no-conditional-statement
217
205
  if (!stream) {
218
206
  try {
219
207
  const result = await db.collection(collection).insertOne(newQueueItem);
220
-
221
208
  if (result.acknowledged) {
222
209
  logger.info(`New noStream BULK queue item for ${operation} ${correlationId} has been made in ${collection}`);
223
210
  return {
@@ -225,16 +212,15 @@ async function _default(MONGO_URI, collection) {
225
212
  queueItemState: _constants.QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS
226
213
  };
227
214
  }
228
-
229
215
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR);
230
216
  } catch (error) {
231
217
  (0, _utils.logError)(error);
232
218
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR);
233
219
  }
234
220
  }
235
- } // Check state that the queueItem has not waited too long and set state
236
-
221
+ }
237
222
 
223
+ // Check state that the queueItem has not waited too long and set state
238
224
  async function checkAndSetState({
239
225
  correlationId,
240
226
  state,
@@ -246,7 +232,6 @@ async function _default(MONGO_URI, collection) {
246
232
  const timeOut = await checkTimeOut({
247
233
  correlationId
248
234
  });
249
-
250
235
  if (timeOut) {
251
236
  return setState({
252
237
  correlationId,
@@ -255,11 +240,10 @@ async function _default(MONGO_URI, collection) {
255
240
  errorStatus
256
241
  });
257
242
  }
258
-
259
243
  return false;
260
- } // Check state that the queueItem has not waited too long and set state
261
-
244
+ }
262
245
 
246
+ // Check state that the queueItem has not waited too long and set state
263
247
  async function checkAndSetImportJobState({
264
248
  correlationId,
265
249
  operation,
@@ -275,7 +259,6 @@ async function _default(MONGO_URI, collection) {
275
259
  operation,
276
260
  importJobState
277
261
  });
278
-
279
262
  if (timeOut) {
280
263
  return setImportJobState({
281
264
  correlationId,
@@ -285,10 +268,8 @@ async function _default(MONGO_URI, collection) {
285
268
  errorStatus
286
269
  });
287
270
  }
288
-
289
271
  return false;
290
272
  }
291
-
292
273
  async function query(params, showParams = {}) {
293
274
  const {
294
275
  showOperations = 0,
@@ -313,7 +294,6 @@ async function _default(MONGO_URI, collection) {
313
294
  logger.debug(`Query result: ${result.length > 0 ? 'Found!' : 'Not found!'}`);
314
295
  return result;
315
296
  }
316
-
317
297
  async function queryById({
318
298
  correlationId,
319
299
  checkModTime = false
@@ -321,28 +301,25 @@ async function _default(MONGO_URI, collection) {
321
301
  const result = await db.collection(collection).findOne({
322
302
  correlationId
323
303
  });
324
-
325
304
  if (checkModTime) {
326
305
  const timeOut = await checkTimeOut({
327
306
  correlationId
328
307
  });
329
-
330
308
  if (timeOut) {
331
309
  return queryById({
332
310
  correlationId
333
311
  });
334
312
  }
335
-
336
313
  return result;
337
314
  }
338
-
339
315
  return result;
340
- } // Check that if the item has waited too long
316
+ }
317
+
318
+ // Check that if the item has waited too long
341
319
  // If the last modification time for the queueItem is older than 1 minute
342
320
  // set state to ABORT and return false, otherwise return true
343
321
  // If the state is already ABORT or ERROR return false
344
322
 
345
-
346
323
  async function checkTimeOut({
347
324
  correlationId
348
325
  }) {
@@ -352,19 +329,17 @@ async function _default(MONGO_URI, collection) {
352
329
  importJobState
353
330
  } = await db.collection(collection).findOne({
354
331
  correlationId
355
- }); // should we check for DONE too?
332
+ });
356
333
 
334
+ // should we check for DONE too?
357
335
  if ([_constants.QUEUE_ITEM_STATE.ABORT, _constants.QUEUE_ITEM_STATE.ERROR, _constants.QUEUE_ITEM_STATE.DONE].includes(oldState)) {
358
336
  logger.silly(`${correlationId} has already state: ${oldState}`);
359
337
  return false;
360
338
  }
361
-
362
339
  const timeoutTime = (0, _moment.default)(modificationTime).add(1, 'm');
363
340
  logger.silly(`timeOut @ ${timeoutTime}`);
364
-
365
341
  if (timeoutTime.isBefore()) {
366
342
  const finalImportJobStates = [_constants.IMPORT_JOB_STATE.ABORT, _constants.IMPORT_JOB_STATE.DONE, _constants.IMPORT_JOB_STATE.EMPTY, _constants.IMPORT_JOB_STATE.ERROR];
367
-
368
343
  if (!finalImportJobStates.includes(importJobState.CREATE)) {
369
344
  // eslint-disable-line
370
345
  await setImportJobState({
@@ -373,7 +348,6 @@ async function _default(MONGO_URI, collection) {
373
348
  importJobState: _constants.IMPORT_JOB_STATE.ABORT
374
349
  });
375
350
  }
376
-
377
351
  if (!finalImportJobStates.includes(importJobState.UPDATE)) {
378
352
  // eslint-disable-line
379
353
  await setImportJobState({
@@ -382,7 +356,6 @@ async function _default(MONGO_URI, collection) {
382
356
  importJobState: _constants.IMPORT_JOB_STATE.ABORT
383
357
  });
384
358
  }
385
-
386
359
  await setState({
387
360
  correlationId,
388
361
  state: _constants.QUEUE_ITEM_STATE.ABORT,
@@ -391,21 +364,17 @@ async function _default(MONGO_URI, collection) {
391
364
  });
392
365
  return false;
393
366
  }
394
-
395
367
  return true;
396
368
  }
397
-
398
369
  async function remove(params) {
399
370
  logger.silly(`${JSON.stringify(params)}`);
400
371
  logger.info(`Removing from Mongo (${collection}) id: ${params.correlationId}`);
401
372
  const clean = (0, _mongoSanitize.default)(params.correlationId);
402
373
  logger.silly(`mongo/remove: clean: ${JSON.stringify(clean)}`);
403
-
404
374
  try {
405
375
  //const metadataResult = await getFileMetadata({filename: clean});
406
376
  //logger.debug(`mongo/remove: metadataResult: ${JSON.stringify(metadataResult)}`);
407
377
  const noContent = await removeContent(params);
408
-
409
378
  if (noContent) {
410
379
  await db.collection(collection).deleteOne({
411
380
  correlationId: clean
@@ -421,15 +390,12 @@ async function _default(MONGO_URI, collection) {
421
390
  });
422
391
  return true;
423
392
  }
424
-
425
393
  logger.error(err.message);
426
394
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, err.message);
427
395
  }
428
-
429
396
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, err.message);
430
397
  }
431
398
  }
432
-
433
399
  async function readContent(correlationId) {
434
400
  logger.info(`Reading content from mongo for id: ${correlationId} in ${collection}`);
435
401
  const clean = (0, _mongoSanitize.default)(correlationId);
@@ -441,43 +407,36 @@ async function _default(MONGO_URI, collection) {
441
407
  const {
442
408
  operationSettings
443
409
  } = result;
444
-
445
410
  if (operationSettings.prio === false && operationSettings.noStream === false) {
446
411
  return {
447
412
  contentType: result.contentType,
448
413
  readStream: gridFSBucket.openDownloadStreamByName(clean)
449
414
  };
450
415
  }
451
-
452
416
  logger.debug(`OperationSetting for ${correlationId}: ${JSON.stringify(operationSettings)}`);
453
417
  throw new _melindaCommons.Error(_httpStatus.default.BAD_REQUEST, {
454
418
  message: `Content is only available for streamBulk jobs. ${correlationId} is not a streamBulk job.`
455
419
  });
456
420
  }
457
-
458
421
  throw new _melindaCommons.Error(_httpStatus.default.NOT_FOUND, {
459
422
  message: `Job ${correlationId} not found.`
460
423
  });
461
424
  }
462
-
463
425
  async function removeContent(params) {
464
426
  logger.info(`Removing content from mongo for id: ${params.correlationId} in ${collection}`);
465
427
  const clean = (0, _mongoSanitize.default)(params.correlationId);
466
428
  const result = await db.collection(collection).findOne({
467
429
  correlationId: clean
468
430
  }); // njsscan-ignore: node_nosqli_injection
469
-
470
431
  logger.silly(`mongo/removeContent: result ${JSON.stringify(result)}`);
471
-
472
432
  if (result) {
473
433
  await gridFSBucket.delete(clean);
474
434
  return true;
475
435
  }
476
-
477
436
  return true;
478
- } // eslint-disable-next-line max-statements
479
-
437
+ }
480
438
 
439
+ // eslint-disable-next-line max-statements
481
440
  function getOne({
482
441
  queueItemState,
483
442
  importJobState = undefined
@@ -486,41 +445,40 @@ async function _default(MONGO_URI, collection) {
486
445
  const cleanQueueItemState = queueItemState ? {
487
446
  queueItemState: (0, _mongoSanitize.default)(queueItemState)
488
447
  } : undefined;
489
-
490
448
  try {
491
449
  // Just queueItemState
492
450
  if (queueItemState && importJobState === undefined) {
493
451
  logger.silly(`Checking DB ${collection} for just ${JSON.stringify(cleanQueueItemState.queueItemState)}`);
494
- return db.collection(collection).findOne({ ...cleanQueueItemState
452
+ return db.collection(collection).findOne({
453
+ ...cleanQueueItemState
495
454
  });
496
- } // importJobState
497
-
455
+ }
498
456
 
457
+ // importJobState
499
458
  if (importJobState && queueItemState === undefined) {
500
459
  logger.silly(`Checking DB ${collection} for ${JSON.stringify(importJobState)}`);
501
- return db.collection(collection).findOne({ ...importJobState
460
+ return db.collection(collection).findOne({
461
+ ...importJobState
502
462
  });
503
- } // importJobState and queueItemState
504
-
463
+ }
505
464
 
465
+ // importJobState and queueItemState
506
466
  if (importJobState && queueItemState) {
507
467
  logger.silly(`Checking DB ${collection} for ${queueItemState} and ${JSON.stringify(importJobState)}`);
508
- return db.collection(collection).findOne({ ...cleanQueueItemState,
468
+ return db.collection(collection).findOne({
469
+ ...cleanQueueItemState,
509
470
  ...importJobState
510
471
  });
511
472
  }
512
-
513
473
  logger.debug(`getOne not working!`);
514
474
  throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, 'Missing parameters, cannot get queueItem');
515
475
  } catch (error) {
516
476
  (0, _utils.logError)(error);
517
477
  }
518
478
  }
519
-
520
479
  function getStream(correlationId) {
521
480
  logger.info(`Forming stream from mongo for ${correlationId} in ${collection}`);
522
481
  const clean = (0, _mongoSanitize.default)(correlationId);
523
-
524
482
  try {
525
483
  // Return content stream
526
484
  return gridFSBucket.openDownloadStreamByName(clean);
@@ -528,7 +486,6 @@ async function _default(MONGO_URI, collection) {
528
486
  (0, _utils.logError)(error);
529
487
  }
530
488
  }
531
-
532
489
  async function pushIds({
533
490
  correlationId,
534
491
  handledIds,
@@ -553,7 +510,6 @@ async function _default(MONGO_URI, collection) {
553
510
  }
554
511
  });
555
512
  }
556
-
557
513
  async function pushMessages({
558
514
  correlationId,
559
515
  messages,
@@ -576,7 +532,6 @@ async function _default(MONGO_URI, collection) {
576
532
  }
577
533
  });
578
534
  }
579
-
580
535
  function setState({
581
536
  correlationId,
582
537
  state,
@@ -588,20 +543,19 @@ async function _default(MONGO_URI, collection) {
588
543
  const stateInQueueItemStates = Object.values(_constants.QUEUE_ITEM_STATE).indexOf(state) > -1;
589
544
  const stateInQueueItemStatesValidator = Object.values(_constants.QUEUE_ITEM_STATE.VALIDATOR).indexOf(state) > -1;
590
545
  const stateInQueueItemStatesImporter = Object.values(_constants.QUEUE_ITEM_STATE.IMPORTER).indexOf(state) > -1;
591
-
592
546
  if (!stateInQueueItemStates && !stateInQueueItemStatesValidator && !stateInQueueItemStatesImporter) {
593
547
  throw new _melindaCommons.Error(_httpStatus.default.BAD_REQUEST, 'Trying to set invalid state');
594
548
  }
595
-
596
549
  const clean = (0, _mongoSanitize.default)(correlationId);
597
550
  const updateValues = {
598
551
  queueItemState: state,
599
552
  modificationTime: (0, _moment.default)().toDate(),
600
553
  errorMessage,
601
554
  errorStatus
602
- }; // Do not update value that are undefined
603
- // eslint-disable-next-line functional/immutable-data
555
+ };
604
556
 
557
+ // Do not update value that are undefined
558
+ // eslint-disable-next-line functional/immutable-data
605
559
  Object.keys(updateValues).forEach(key => updateValues[key] === undefined && delete updateValues[key]);
606
560
  return db.collection(collection).findOneAndUpdate({
607
561
  correlationId: clean
@@ -614,7 +568,6 @@ async function _default(MONGO_URI, collection) {
614
568
  returnNewDocument: true
615
569
  });
616
570
  }
617
-
618
571
  function setImportJobState({
619
572
  correlationId,
620
573
  operation,
@@ -624,15 +577,12 @@ async function _default(MONGO_URI, collection) {
624
577
  logger.info(`Setting queue-item importJobState: {${operation}: ${importJobState}} for ${correlationId}`);
625
578
  const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId);
626
579
  const cleanImportJobState = (0, _mongoSanitize.default)(importJobState);
627
-
628
580
  if (!(operation in _constants.OPERATIONS)) {
629
581
  throw new _melindaCommons.Error('400', 'Invalid operation for import job state');
630
582
  }
631
-
632
583
  if (!(cleanImportJobState in _constants.IMPORT_JOB_STATE)) {
633
584
  throw new _melindaCommons.Error('400', 'Invalid import job state');
634
585
  }
635
-
636
586
  const newJobState = operation === _constants.OPERATIONS.CREATE ? {
637
587
  'importJobState.CREATE': cleanImportJobState
638
588
  } : {
@@ -641,7 +591,8 @@ async function _default(MONGO_URI, collection) {
641
591
  return db.collection(collection).findOneAndUpdate({
642
592
  correlationId: cleanCorrelationId
643
593
  }, {
644
- $set: { ...newJobState,
594
+ $set: {
595
+ ...newJobState,
645
596
  modificationTime: (0, _moment.default)().toDate()
646
597
  }
647
598
  }, {
@@ -651,7 +602,6 @@ async function _default(MONGO_URI, collection) {
651
602
  returnNewDocument: true
652
603
  });
653
604
  }
654
-
655
605
  async function setOperation({
656
606
  correlationId,
657
607
  operation
@@ -678,7 +628,8 @@ async function _default(MONGO_URI, collection) {
678
628
  },
679
629
  returnNewDocument: true
680
630
  });
681
- return result.ok; // logger.debug(JSON.stringify(result));
631
+ return result.ok;
632
+ // logger.debug(JSON.stringify(result));
682
633
  }
683
634
 
684
635
  async function setOperations({
@@ -710,7 +661,8 @@ async function _default(MONGO_URI, collection) {
710
661
  },
711
662
  returnNewDocument: true
712
663
  });
713
- return result.ok; // logger.debug(JSON.stringify(result));
664
+ return result.ok;
665
+ // logger.debug(JSON.stringify(result));
714
666
  }
715
667
 
716
668
  async function addBlobSize({
@@ -736,7 +688,6 @@ async function _default(MONGO_URI, collection) {
736
688
  logger.verbose(`AddBlobSizeResult in mongo: ${JSON.stringify(result)}`);
737
689
  return result;
738
690
  }
739
-
740
691
  async function setBlobSize({
741
692
  correlationId,
742
693
  blobSize