@natlibfi/melinda-rest-api-commons 4.2.5 → 5.0.0-alpha.2

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.
Files changed (55) hide show
  1. package/.github/workflows/melinda-node-tests.yml +9 -6
  2. package/dist/amqp.js +60 -151
  3. package/dist/amqp.js.map +7 -1
  4. package/dist/constants.js +40 -51
  5. package/dist/constants.js.map +7 -1
  6. package/dist/helpers/conversion.js +39 -57
  7. package/dist/helpers/conversion.js.map +7 -1
  8. package/dist/helpers/fix-constants.js +40 -47
  9. package/dist/helpers/fix-constants.js.map +7 -1
  10. package/dist/helpers/fix-handle-tempurns.js +23 -73
  11. package/dist/helpers/fix-handle-tempurns.js.map +7 -1
  12. package/dist/helpers/fix-strip-f884s.js +44 -94
  13. package/dist/helpers/fix-strip-f884s.js.map +7 -1
  14. package/dist/helpers/fix-utils.js +7 -22
  15. package/dist/helpers/fix-utils.js.map +7 -1
  16. package/dist/helpers/fix.js +62 -122
  17. package/dist/helpers/fix.js.map +7 -1
  18. package/dist/helpers/validation.js +12 -30
  19. package/dist/helpers/validation.js.map +7 -1
  20. package/dist/index.js +10 -109
  21. package/dist/index.js.map +7 -1
  22. package/dist/mongo.js +173 -509
  23. package/dist/mongo.js.map +7 -1
  24. package/dist/mongoLog.js +92 -317
  25. package/dist/mongoLog.js.map +7 -1
  26. package/dist/utils.js +46 -155
  27. package/dist/utils.js.map +7 -1
  28. package/eslint.config.js +53 -0
  29. package/package.json +23 -96
  30. package/tests/{amqp.health.spec.js → amqp.healthtest.js} +2 -2
  31. package/tests/{amqp.tests.spec.js → amqp.tests.localtest.js} +46 -46
  32. package/tests/helpers/{conversion.spec.js → conversion.test.js} +38 -25
  33. package/tests/helpers/{fix.spec.js → fix.test.js} +6 -6
  34. package/tests/helpers/{validation.spec.js → validation.test.js} +12 -9
  35. package/tests/{mongo-add-blob-size.spec.js → mongo-add-blob-size.test.js} +6 -6
  36. package/tests/{mongo-check-and-check-state.spec.js → mongo-check-and-check-state.test.js} +7 -7
  37. package/tests/{mongo-check-and-set-import-job-state.spec.js → mongo-check-and-set-import-job-state.test.js} +7 -7
  38. package/tests/{mongo-check-timeout.spec.js → mongo-check-timeout.test.js} +7 -7
  39. package/tests/{mongo-create-bulk.spec.js → mongo-create-bulk.test.js} +5 -5
  40. package/tests/{mongo-create-prio.spec.js → mongo-create-prio.test.js} +6 -6
  41. package/tests/{mongo-get-one.spec.js → mongo-get-one.test.js} +7 -7
  42. package/tests/{mongo-get-stream.spec.js → mongo-get-stream.test.js} +7 -7
  43. package/tests/{mongo-push-ids.spec.js → mongo-push-ids.test.js} +5 -5
  44. package/tests/{mongo-push-messages.spec.js → mongo-push-messages.test.js} +6 -6
  45. package/tests/{mongo-query-by-id.spec.js → mongo-query-by-id.test.js} +7 -7
  46. package/tests/{mongo-query.spec.js → mongo-query.test.js} +7 -7
  47. package/tests/{mongo-read-content.spec.js → mongo-read-content.test.js} +8 -8
  48. package/tests/{mongo-remove.spec.js → mongo-remove.test.js} +6 -6
  49. package/tests/{mongo-set-blob-size.spec.js → mongo-set-blob-size.test.js} +6 -6
  50. package/tests/{mongo-set-import-job-state.spec.js → mongo-set-import-job-state.test.js} +6 -6
  51. package/tests/{mongo-set-operation.spec.js → mongo-set-operation.test.js} +6 -6
  52. package/tests/{mongo-set-operations.spec.js → mongo-set-operations.test.js} +6 -6
  53. package/tests/{mongo-set-state.spec.js → mongo-set-state.test.js} +7 -7
  54. package/tests/{mongoLog.spec.js → mongoLog.test.js} +10 -11
  55. package/tests/testUtils.js +9 -8
package/dist/mongo.js CHANGED
@@ -1,97 +1,25 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.default = _default;
8
- var _mongodb = require("mongodb");
9
- var _melindaBackendCommons = require("@natlibfi/melinda-backend-commons");
10
- var _melindaCommons = require("@natlibfi/melinda-commons");
11
- var _constants = require("./constants");
12
- var _utils = require("./utils.js");
13
- var _moment = _interopRequireDefault(require("moment"));
14
- var _httpStatus = _interopRequireDefault(require("http-status"));
15
- var _mongoSanitize = _interopRequireDefault(require("mongo-sanitize"));
16
- var _debug = _interopRequireDefault(require("debug"));
17
- /* eslint-disable max-lines */
18
-
19
- //import isDeepStrictEqual from 'util';
20
-
21
- /* QueueItem:
22
- {
23
- "correlationId":"FOO",
24
- "cataloger":"xxx0000",
25
- "oCatalogerIn":"xxx0000"
26
- "operation":"UPDATE",
27
- "operations":["UPDATE", "CREATE"]
28
- "contentType":"application/json",
29
- "recordLoadParams": {
30
- "pActiveLibrary": "XXX00",
31
- "pInputFile": "filename.seq",
32
- "pRejectFile": "filename.rej",
33
- "pLogFile": "filename.syslog",
34
- "pOldNew": "NEW"
35
- },
36
- "queueItemState":"PENDING_QUEUING",
37
- "importJobState": {
38
- "CREATE": "EMPTY",
39
- "UPDATE": "EMPTY"
40
- },
41
- blobSize: 1,
42
- records: [],
43
- errorMessage: '',
44
- errorStatus: '',
45
- "creationTime":"2020-01-01T00:00:00.000Z",
46
- "modificationTime":"2020-01-01T00:00:01.000Z",
47
- }
48
- */
49
-
50
- async function _default(MONGO_URI, collection, db = 'rest-api') {
51
- const logger = (0, _melindaBackendCommons.createLogger)();
52
- const debug = (0, _debug.default)('@natlibfi/melinda-rest-api-commons/mongo');
53
- const debugDev = debug.extend(':dev');
54
-
55
- // Connect to mongo (MONGO)
56
- const client = await _mongodb.MongoClient.connect(MONGO_URI);
1
+ import { MongoClient, GridFSBucket, MongoDriverError } from "mongodb";
2
+ import moment from "moment";
3
+ import httpStatus from "http-status";
4
+ import sanitize from "mongo-sanitize";
5
+ import createDebugLogger from "debug";
6
+ import { createLogger } from "@natlibfi/melinda-backend-commons";
7
+ import { Error as ApiError, parseBoolean } from "@natlibfi/melinda-commons";
8
+ import { QUEUE_ITEM_STATE, IMPORT_JOB_STATE, OPERATIONS } from "./constants.js";
9
+ import { logError } from "./utils.js";
10
+ export default async function(MONGO_URI, collection, db = "rest-api") {
11
+ const logger = createLogger();
12
+ const debug = createDebugLogger("@natlibfi/melinda-rest-api-commons/mongo");
13
+ const debugDev = debug.extend(":dev");
14
+ const client = await MongoClient.connect(MONGO_URI);
57
15
  const dbConnection = client.db(db);
58
- const gridFSBucket = new _mongodb.GridFSBucket(dbConnection, {
59
- bucketName: collection
60
- });
16
+ const gridFSBucket = new GridFSBucket(dbConnection, { bucketName: collection });
61
17
  const operator = dbConnection.collection(collection);
62
18
  debugDev(`mongo: ${MONGO_URI}, db: ${db}, collection: ${collection}`);
63
- return {
64
- createPrio,
65
- createBulk,
66
- checkAndSetState,
67
- checkAndSetImportJobState,
68
- query,
69
- createProjection,
70
- queryById,
71
- checkTimeOut,
72
- remove,
73
- readContent,
74
- removeContent,
75
- getOne,
76
- getStream,
77
- setState,
78
- setImportJobState,
79
- pushIds,
80
- pushMessages,
81
- setOperation,
82
- setOperations,
83
- addBlobSize,
84
- setBlobSize
85
- };
86
- async function createPrio({
87
- correlationId,
88
- cataloger,
89
- oCatalogerIn,
90
- operation,
91
- operationSettings
92
- }) {
93
- debugDev('createPrio');
94
- const time = (0, _moment.default)().toDate();
19
+ return { createPrio, createBulk, checkAndSetState, checkAndSetImportJobState, query, createProjection, queryById, checkTimeOut, remove, readContent, removeContent, getOne, getStream, setState, setImportJobState, pushIds, pushMessages, setOperation, setOperations, addBlobSize, setBlobSize };
20
+ async function createPrio({ correlationId, cataloger, oCatalogerIn, operation, operationSettings }) {
21
+ debugDev("createPrio");
22
+ const time = moment().toDate();
95
23
  const newQueueItem = {
96
24
  correlationId,
97
25
  cataloger,
@@ -102,16 +30,16 @@ async function _default(MONGO_URI, collection, db = 'rest-api') {
102
30
  prio: true,
103
31
  ...operationSettings
104
32
  },
105
- queueItemState: _constants.QUEUE_ITEM_STATE.VALIDATOR.PENDING_VALIDATION,
33
+ queueItemState: QUEUE_ITEM_STATE.VALIDATOR.PENDING_VALIDATION,
106
34
  blobSize: 1,
107
35
  importJobState: {
108
- CREATE: _constants.IMPORT_JOB_STATE.EMPTY,
109
- UPDATE: _constants.IMPORT_JOB_STATE.EMPTY,
110
- FIX: _constants.IMPORT_JOB_STATE.EMPTY
36
+ CREATE: IMPORT_JOB_STATE.EMPTY,
37
+ UPDATE: IMPORT_JOB_STATE.EMPTY,
38
+ FIX: IMPORT_JOB_STATE.EMPTY
111
39
  },
112
40
  records: [],
113
- errorMessage: '',
114
- errorStatus: '',
41
+ errorMessage: "",
42
+ errorStatus: "",
115
43
  creationTime: time,
116
44
  modificationTime: time
117
45
  };
@@ -123,28 +51,15 @@ async function _default(MONGO_URI, collection, db = 'rest-api') {
123
51
  logger.info(`New PRIO queue item for ${operation} ${correlationId} has been made in ${collection}`);
124
52
  return;
125
53
  }
126
- // TEST-COVERAGE: this error is not (currently) tested
127
- throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR);
54
+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);
128
55
  } catch (error) {
129
- // TEST-COVERAGE: this error is not (currently) tested
130
- const errorMessage = error.payload || error.message || '';
131
- (0, _utils.logError)(error);
132
- throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, `Mongo errored: ${errorMessage}`);
56
+ const errorMessage = error.payload || error.message || "";
57
+ logError(error);
58
+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, `Mongo errored: ${errorMessage}`);
133
59
  }
134
60
  }
135
-
136
- // eslint-disable-next-line max-statements
137
- async function createBulk({
138
- correlationId,
139
- cataloger,
140
- oCatalogerIn,
141
- operation,
142
- contentType,
143
- recordLoadParams,
144
- stream,
145
- operationSettings
146
- }) {
147
- const time = (0, _moment.default)().toDate();
61
+ async function createBulk({ correlationId, cataloger, oCatalogerIn, operation, contentType, recordLoadParams, stream, operationSettings }) {
62
+ const time = moment().toDate();
148
63
  const newQueueItem = {
149
64
  correlationId,
150
65
  cataloger,
@@ -157,27 +72,25 @@ async function _default(MONGO_URI, collection, db = 'rest-api') {
157
72
  },
158
73
  contentType,
159
74
  recordLoadParams,
160
- queueItemState: stream ? _constants.QUEUE_ITEM_STATE.VALIDATOR.UPLOADING : _constants.QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS,
75
+ queueItemState: stream ? QUEUE_ITEM_STATE.VALIDATOR.UPLOADING : QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS,
161
76
  blobSize: 0,
162
77
  importJobState: {
163
- CREATE: _constants.IMPORT_JOB_STATE.EMPTY,
164
- UPDATE: _constants.IMPORT_JOB_STATE.EMPTY,
165
- FIX: _constants.IMPORT_JOB_STATE.EMPTY
78
+ CREATE: IMPORT_JOB_STATE.EMPTY,
79
+ UPDATE: IMPORT_JOB_STATE.EMPTY,
80
+ FIX: IMPORT_JOB_STATE.EMPTY
166
81
  },
167
82
  records: [],
168
- errorMessage: '',
169
- errorStatus: '',
83
+ errorMessage: "",
84
+ errorStatus: "",
170
85
  creationTime: time,
171
86
  modificationTime: time
172
87
  };
173
-
174
- // eslint-disable-next-line functional/no-conditional-statements
175
88
  if (stream) {
176
89
  debug(`Creating streamBulk`);
177
90
  try {
178
91
  await new Promise((resolve, reject) => {
179
92
  const outputStream = gridFSBucket.openUploadStream(correlationId);
180
- stream.on('error', reject).on('data', chunk => outputStream.write(chunk)).on('end', () => outputStream.end(undefined, undefined, () => {
93
+ stream.on("error", reject).on("data", (chunk) => outputStream.write(chunk)).on("end", () => outputStream.end(void 0, void 0, () => {
181
94
  resolve(correlationId);
182
95
  }));
183
96
  });
@@ -185,115 +98,58 @@ async function _default(MONGO_URI, collection, db = 'rest-api') {
185
98
  debug(`New BULK queue item for ${operation} ${correlationId} has been made in ${collection}!`);
186
99
  return operator.insertOne(newQueueItem);
187
100
  } catch (error) {
188
- const errorMessage = error.payload || error.message || '';
189
- (0, _utils.logError)(error);
190
- throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, `Mongo errored: ${errorMessage}`);
101
+ const errorMessage = error.payload || error.message || "";
102
+ logError(error);
103
+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, `Mongo errored: ${errorMessage}`);
191
104
  }
192
105
  }
193
106
  logger.debug(`No stream`);
194
107
  debug(`Creating noStreamBulk`);
195
- // eslint-disable-next-line functional/no-conditional-statements
196
108
  if (!stream) {
197
109
  try {
198
110
  const result = await operator.insertOne(newQueueItem);
199
111
  if (result.acknowledged) {
200
112
  logger.info(`New noStream BULK queue item for ${operation} ${correlationId} has been made in ${collection}`);
201
113
  debug(`New noStream BULK queue item for ${operation} ${correlationId} has been made in ${collection}`);
202
- return {
203
- correlationId,
204
- queueItemState: _constants.QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS
205
- };
114
+ return { correlationId, queueItemState: QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS };
206
115
  }
207
- // TEST-COVERAGE: this error is not (currently) tested
208
- throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR);
116
+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);
209
117
  } catch (error) {
210
- // TEST-COVERAGE: this error is not (currently) tested
211
- const errorMessage = error.payload || error.message || '';
212
- (0, _utils.logError)(error);
213
- throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, `Mongo errored: ${errorMessage}`);
118
+ const errorMessage = error.payload || error.message || "";
119
+ logError(error);
120
+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, `Mongo errored: ${errorMessage}`);
214
121
  }
215
122
  }
216
123
  }
217
-
218
- // Check state that the queueItem has not waited too long and set state
219
- // Optionally set also queueItems errorStatus & errorMessage
220
- async function checkAndSetState({
221
- correlationId,
222
- state,
223
- errorMessage = undefined,
224
- errorStatus = undefined
225
- }) {
226
- // checkTimeOut returns true, if queueItem is fresher than 1 minute and it's state is not ABORT/ERROR/DONE
227
- // otherwise it sets queueItem and importJobStates to state ABORT and add errorStatus and errorMessage (408, 'Timeout')
228
- const timeOut = await checkTimeOut({
229
- correlationId
230
- });
124
+ async function checkAndSetState({ correlationId, state, errorMessage = void 0, errorStatus = void 0 }) {
125
+ const timeOut = await checkTimeOut({ correlationId });
231
126
  if (timeOut) {
232
- return setState({
233
- correlationId,
234
- state,
235
- errorMessage,
236
- errorStatus
237
- });
127
+ return setState({ correlationId, state, errorMessage, errorStatus });
238
128
  }
239
129
  return false;
240
130
  }
241
-
242
- // Check state that the queueItem has not waited too long and set importJobState
243
- // Note: checkAndSetImportJobState cannot be used to set queueItems errorStatus & errorMessage (expect in case of a TimeOut)
244
- async function checkAndSetImportJobState({
245
- correlationId,
246
- operation,
247
- importJobState
248
- }) {
249
- // checkTimeOut returns true, if queueItem is fresher than 1 minute and it's state is not ABORT/ERROR/DONE
250
- // otherwise it sets queueItem and importJobStates to state ABORT and errorStatue and errorMessage (408, 'Timeout')
131
+ async function checkAndSetImportJobState({ correlationId, operation, importJobState }) {
251
132
  logger.debug(`${correlationId}, ${importJobState}, ${operation}`);
252
- const timeOut = await checkTimeOut({
253
- correlationId,
254
- operation,
255
- importJobState
256
- });
133
+ const timeOut = await checkTimeOut({ correlationId, operation, importJobState });
257
134
  if (timeOut) {
258
- return setImportJobState({
259
- correlationId,
260
- operation,
261
- importJobState
262
- });
135
+ return setImportJobState({ correlationId, operation, importJobState });
263
136
  }
264
137
  return false;
265
138
  }
266
139
  async function query(params, showParams = {}) {
267
140
  logger.debug(`Querying: ${JSON.stringify(params)}, ${JSON.stringify(showParams)}`);
268
141
  debug(`Querying: ${JSON.stringify(params)}, ${JSON.stringify(showParams)}`);
269
- const {
270
- limit = 1000,
271
- skip = 0,
272
- ...rest
273
- } = params;
274
- const result = await operator.find(rest, {
275
- projection: createProjection(showParams)
276
- }).limit(parseInt(limit, 10)).skip(parseInt(skip, 10)).toArray();
277
- logger.debug(`Query result: ${result.length > 0 ? 'Found!' : 'Not found!'}`);
142
+ const { limit = 1e3, skip = 0, ...rest } = params;
143
+ const result = await operator.find(rest, { projection: createProjection(showParams) }).limit(parseInt(limit, 10)).skip(parseInt(skip, 10)).toArray();
144
+ logger.debug(`Query result: ${result.length > 0 ? "Found!" : "Not found!"}`);
278
145
  logger.silly(`${JSON.stringify(result)}`);
279
146
  debug(`${JSON.stringify(result)}`);
280
147
  return result;
281
148
  }
282
-
283
- // We default to NOT showing operations, operationSettings, recordLoadParams and importJobState when a queueItem is queried
284
- // These can all be shown with showAll
285
- // Single fields can be shown by showOperation, showOperationSettings, showRecordLoadParams and showImportJobState
286
-
287
149
  function createProjection(showParams = {}) {
288
150
  logger.silly(`Creating projection for query: ${JSON.stringify(showParams)}`);
289
151
  debug(`Creating projection for query: ${JSON.stringify(showParams)}`);
290
- const {
291
- showAll = 0,
292
- showOperations = 0,
293
- showOperationSettings = 0,
294
- showRecordLoadParams = 0,
295
- showImportJobState = 0
296
- } = showParams;
152
+ const { showAll = 0, showOperations = 0, showOperationSettings = 0, showRecordLoadParams = 0, showImportJobState = 0 } = showParams;
297
153
  const combinedShowParams = {
298
154
  showAll,
299
155
  showOperations,
@@ -304,27 +160,22 @@ async function _default(MONGO_URI, collection, db = 'rest-api') {
304
160
  logger.debug(`showAll: ${showAll}, showOperations: ${showOperations}, showOperationSettings: ${showOperationSettings}, showRecordLoadParams: ${showRecordLoadParams}, showImportJobState: ${showImportJobState}`);
305
161
  debug(`showAll: ${showAll}, showOperations: ${showOperations}, showOperationSettings: ${showOperationSettings}, showRecordLoadParams: ${showRecordLoadParams}, showImportJobState: ${showImportJobState}`);
306
162
  debug(`${JSON.stringify(combinedShowParams)}`);
307
-
308
- // NOTE: parseBoolean parses any non-empty, non-"false" string as true!
309
- if ((0, _melindaCommons.parseBoolean)(showAll)) {
310
- //if (showAll === true || showAll === '1' || showAll === 1) {
163
+ if (parseBoolean(showAll)) {
311
164
  debug(`ShowAll: ${showAll}`);
312
165
  return {
313
166
  _id: 0
314
167
  };
315
168
  }
316
169
  const showParamToField = {
317
- 'showOperations': 'operations',
318
- 'showOperationSettings': 'operationSettings',
319
- 'showRecordLoadParams': 'recordLoadParams',
320
- 'showImportJobState': 'importJobState'
170
+ "showOperations": "operations",
171
+ "showOperationSettings": "operationSettings",
172
+ "showRecordLoadParams": "recordLoadParams",
173
+ "showImportJobState": "importJobState"
321
174
  };
322
- const result = Object.keys(combinedShowParams)
323
- //.filter(param => param !== 'showAll' && combinedShowParams[param] !== true && combinedShowParams[param] !== 1 && combinedShowParams[param] !== '1')
324
- .filter(param => param !== 'showAll' && !(0, _melindaCommons.parseBoolean)(combinedShowParams[param])).filter(param => showParamToField[param]).map(param => showParamToField[param]);
175
+ const result = Object.keys(combinedShowParams).filter((param) => param !== "showAll" && !parseBoolean(combinedShowParams[param])).filter((param) => showParamToField[param]).map((param) => showParamToField[param]);
325
176
  logger.silly(`We want to exclude from projection: ${JSON.stringify(result)}`);
326
177
  debug(`We want to exclude from projection: ${JSON.stringify(result)}`);
327
- const excludeObject = Object.fromEntries(result.map(param => [param, 0]));
178
+ const excludeObject = Object.fromEntries(result.map((param) => [param, 0]));
328
179
  logger.silly(`We want to exclude from projection: ${JSON.stringify(excludeObject)}`);
329
180
  debug(`We want to exclude from projection: ${JSON.stringify(excludeObject)}`);
330
181
  return {
@@ -332,146 +183,79 @@ async function _default(MONGO_URI, collection, db = 'rest-api') {
332
183
  ...excludeObject
333
184
  };
334
185
  }
335
-
336
- // Note: edited in v4.2.4 to return queueItem *after* possible timout has aborted it
337
- // Note: previous versions returned queueItem *before* its state/queueItemState is timeOuted
338
- async function queryById({
339
- correlationId,
340
- checkModTime = false
341
- }) {
186
+ async function queryById({ correlationId, checkModTime = false }) {
342
187
  if (checkModTime) {
343
188
  debug(`queryById checkModTime: ${checkModTime}`);
344
- await checkTimeOut({
345
- correlationId
346
- });
347
- return queryById({
348
- correlationId
349
- });
189
+ await checkTimeOut({ correlationId });
190
+ return queryById({ correlationId });
350
191
  }
351
- const result = await operator.findOne({
352
- correlationId
353
- }, {
354
- projection: {
355
- _id: 0
356
- }
357
- });
192
+ const result = await operator.findOne({ correlationId }, { projection: { _id: 0 } });
358
193
  return result;
359
194
  }
360
-
361
- // Check that if the item has waited too long
362
- // If the last modification time for the queueItem is older than 1 minute
363
- // set state to ABORT and return false, otherwise return true
364
- // If the state is already ABORT or ERROR or DONE return false
365
-
366
- async function checkTimeOut({
367
- correlationId
368
- }) {
369
- const {
370
- modificationTime,
371
- queueItemState: oldState,
372
- importJobState
373
- } = await operator.findOne({
374
- correlationId
375
- });
376
- //debug(`${modificationTime} - oldState: ${oldState}`);
377
- // should we check for DONE too?
378
- if ([_constants.QUEUE_ITEM_STATE.ABORT, _constants.QUEUE_ITEM_STATE.ERROR, _constants.QUEUE_ITEM_STATE.DONE].includes(oldState)) {
195
+ async function checkTimeOut({ correlationId }) {
196
+ const { modificationTime, queueItemState: oldState, importJobState } = await operator.findOne({ correlationId });
197
+ if ([QUEUE_ITEM_STATE.ABORT, QUEUE_ITEM_STATE.ERROR, QUEUE_ITEM_STATE.DONE].includes(oldState)) {
379
198
  logger.silly(`${correlationId} has already state: ${oldState}`);
380
199
  return false;
381
200
  }
382
- const timeoutTime = (0, _moment.default)(modificationTime).add(1, 'm');
201
+ const timeoutTime = moment(modificationTime).add(1, "m");
383
202
  logger.silly(`${correlationId} timeOut @ ${timeoutTime}`);
384
203
  if (timeoutTime.isBefore()) {
385
- const finalImportJobStates = [_constants.IMPORT_JOB_STATE.ABORT, _constants.IMPORT_JOB_STATE.DONE, _constants.IMPORT_JOB_STATE.EMPTY, _constants.IMPORT_JOB_STATE.ERROR];
204
+ const finalImportJobStates = [IMPORT_JOB_STATE.ABORT, IMPORT_JOB_STATE.DONE, IMPORT_JOB_STATE.EMPTY, IMPORT_JOB_STATE.ERROR];
386
205
  if (!finalImportJobStates.includes(importJobState.CREATE)) {
387
- // eslint-disable-line
388
- await setImportJobState({
389
- correlationId,
390
- operation: 'CREATE',
391
- importJobState: _constants.IMPORT_JOB_STATE.ABORT
392
- });
206
+ await setImportJobState({ correlationId, operation: "CREATE", importJobState: IMPORT_JOB_STATE.ABORT });
393
207
  }
394
208
  if (!finalImportJobStates.includes(importJobState.UPDATE)) {
395
- // eslint-disable-line
396
- await setImportJobState({
397
- correlationId,
398
- operation: 'UPDATE',
399
- importJobState: _constants.IMPORT_JOB_STATE.ABORT
400
- });
209
+ await setImportJobState({ correlationId, operation: "UPDATE", importJobState: IMPORT_JOB_STATE.ABORT });
401
210
  }
402
211
  if (!finalImportJobStates.includes(importJobState.FIX)) {
403
- // eslint-disable-line
404
- await setImportJobState({
405
- correlationId,
406
- operation: 'FIX',
407
- importJobState: _constants.IMPORT_JOB_STATE.ABORT
408
- });
212
+ await setImportJobState({ correlationId, operation: "FIX", importJobState: IMPORT_JOB_STATE.ABORT });
409
213
  }
410
- await setState({
411
- correlationId,
412
- state: _constants.QUEUE_ITEM_STATE.ABORT,
413
- errorStatus: _httpStatus.default.REQUEST_TIMEOUT,
414
- errorMessage: `Timeout in ${oldState}`
415
- });
214
+ await setState({ correlationId, state: QUEUE_ITEM_STATE.ABORT, errorStatus: httpStatus.REQUEST_TIMEOUT, errorMessage: `Timeout in ${oldState}` });
416
215
  return false;
417
216
  }
418
217
  return true;
419
218
  }
420
-
421
- // eslint-disable-next-line max-statements
422
219
  async function remove(params) {
423
220
  logger.silly(`${JSON.stringify(params)}`);
424
221
  logger.info(`Removing from Mongo (${collection}) id: ${params.correlationId}`);
425
222
  debug(`${JSON.stringify(params)}`);
426
223
  debug(`Removing from Mongo (${collection}) id: ${params.correlationId}`);
427
- const clean = (0, _mongoSanitize.default)(params.correlationId);
224
+ const clean = sanitize(params.correlationId);
428
225
  logger.silly(`mongo/remove: clean: ${JSON.stringify(clean)}`);
429
226
  debug(`mongo/remove: clean: ${JSON.stringify(clean)}`);
430
227
  try {
431
- //const metadataResult = await getFileMetadata({filename: clean});
432
- //logger.debug(`mongo/remove: metadataResult: ${JSON.stringify(metadataResult)}`);
433
- const noContent = await removeContent({
434
- correlationId: params.correlationId
435
- });
228
+ const noContent = await removeContent({ correlationId: params.correlationId });
436
229
  debug(`noContent (removeContent result): ${JSON.stringify(noContent)}`);
437
230
  if (noContent) {
438
- const deleteResult = await operator.deleteOne({
439
- correlationId: clean
440
- });
231
+ const deleteResult = await operator.deleteOne({ correlationId: clean });
441
232
  debug(`deleteResult: ${JSON.stringify(deleteResult)}`);
442
233
  return true;
443
234
  }
444
235
  } catch (err) {
445
- // TEST-COVERAGE: this error is not (currently) tested
446
- if (err instanceof _mongodb.MongoDriverError) {
236
+ if (err instanceof MongoDriverError) {
447
237
  debug(err);
448
- if (err.message.indexOf('File not found for id') !== -1) {
238
+ if (err.message.indexOf("File not found for id") !== -1) {
449
239
  logger.silly(`mongo/remove: File not found, removing queueItem ${JSON.stringify(clean)} from ${collection}`);
450
240
  debug(`mongo/remove: File not found, removing queueItem ${JSON.stringify(clean)} from ${collection}`);
451
- await operator.deleteOne({
452
- correlationId: clean
453
- });
241
+ await operator.deleteOne({ correlationId: clean });
454
242
  return true;
455
243
  }
456
244
  logger.error(err.message);
457
- throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, err.message);
245
+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, err.message);
458
246
  }
459
- throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, err.message);
247
+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, err.message);
460
248
  }
461
249
  }
462
250
  async function readContent(correlationId) {
463
251
  logger.info(`Reading content from mongo for id: ${correlationId} in ${collection}`);
464
252
  debug(`Reading content from mongo for id: ${correlationId} in ${collection}`);
465
- const clean = (0, _mongoSanitize.default)(correlationId);
253
+ const clean = sanitize(correlationId);
466
254
  debug(clean);
467
- const result = await operator.findOne({
468
- correlationId: clean
469
- }); // njsscan-ignore: node_nosqli_injection
255
+ const result = await operator.findOne({ correlationId: clean });
470
256
  debug(result);
471
257
  if (result) {
472
- const {
473
- operationSettings
474
- } = result;
258
+ const { operationSettings } = result;
475
259
  if (operationSettings.prio === false && operationSettings.noStream === false) {
476
260
  return {
477
261
  contentType: result.contentType,
@@ -481,24 +265,17 @@ async function _default(MONGO_URI, collection, db = 'rest-api') {
481
265
  logger.debug(`OperationSettings for ${correlationId}: ${JSON.stringify(operationSettings)}`);
482
266
  debug(`OperationSettings for ${correlationId}: ${JSON.stringify(operationSettings)}`);
483
267
  debug(`Content is only available for streamBulk jobs. ${correlationId} is not a streamBulk job.`);
484
- throw new _melindaCommons.Error(_httpStatus.default.BAD_REQUEST, {
485
- message: `Content is only available for streamBulk jobs. ${correlationId} is not a streamBulk job.`
486
- });
268
+ throw new ApiError(httpStatus.BAD_REQUEST, { message: `Content is only available for streamBulk jobs. ${correlationId} is not a streamBulk job.` });
487
269
  }
488
- throw new _melindaCommons.Error(_httpStatus.default.NOT_FOUND, {
489
- message: `Job ${correlationId} not found.`
490
- });
270
+ throw new ApiError(httpStatus.NOT_FOUND, { message: `Job ${correlationId} not found.` });
491
271
  }
492
272
  async function removeContent(params) {
493
273
  logger.info(`Removing content from mongo for id: ${params.correlationId} in ${collection}`);
494
274
  debug(`Removing content from mongo for id: ${params.correlationId} in ${collection}`);
495
- const clean = (0, _mongoSanitize.default)(params.correlationId);
496
- const result = await gridFSBucket.find({
497
- filename: clean
498
- }).toArray();
275
+ const clean = sanitize(params.correlationId);
276
+ const result = await gridFSBucket.find({ filename: clean }).toArray();
499
277
  debug(`mongo/removeContent: find bucket result ${JSON.stringify(result)}`);
500
278
  if (result.length > 0) {
501
- // Note: we assume and handle just one file for filename!
502
279
  const [firstBucketResult] = result;
503
280
  const fileId = firstBucketResult._id;
504
281
  await gridFSBucket.delete(fileId);
@@ -507,250 +284,158 @@ async function _default(MONGO_URI, collection, db = 'rest-api') {
507
284
  logger.debug(`No files for ${params.correlationId} to delete`);
508
285
  return true;
509
286
  }
510
- function getOne({
511
- queueItemState,
512
- importJobState = undefined
513
- }) {
514
- //params example: "queueItemState": "IMPORTER.IN_QUEUE", "importJobState":{"importJobState.UPDATE": "IN_QUEUE"}
287
+ function getOne({ queueItemState, importJobState = void 0 }) {
515
288
  logger.silly(`queueItemState: ${queueItemState}, importJobState: ${JSON.stringify(importJobState)}`);
516
- //debug(`queueItemState: ${queueItemState}, importJobState: ${JSON.stringify(importJobState)}`);
517
- const cleanQueueItemState = queueItemState ? {
518
- queueItemState: (0, _mongoSanitize.default)(queueItemState)
519
- } : undefined;
520
- const options = {
521
- projection: {
522
- _id: 0
523
- }
524
- };
289
+ const cleanQueueItemState = queueItemState ? { queueItemState: sanitize(queueItemState) } : void 0;
290
+ const options = { projection: { _id: 0 } };
525
291
  try {
526
- // Just queueItemState
527
- if (queueItemState && importJobState === undefined) {
292
+ if (queueItemState && importJobState === void 0) {
528
293
  logger.silly(`Checking DB ${collection} for just ${JSON.stringify(cleanQueueItemState.queueItemState)}`);
529
- //debug(`Checking DB ${collection} for just ${JSON.stringify(cleanQueueItemState.queueItemState)}`);
530
- return operator.findOne({
531
- ...cleanQueueItemState
532
- }, options);
294
+ return operator.findOne({ ...cleanQueueItemState }, options);
533
295
  }
534
-
535
- // importJobState
536
- if (importJobState && queueItemState === undefined) {
296
+ if (importJobState && queueItemState === void 0) {
537
297
  logger.silly(`Checking DB ${collection} for ${JSON.stringify(importJobState)}`);
538
- //debug(`Checking DB ${collection} for ${JSON.stringify(importJobState)}`);
539
- return operator.findOne({
540
- ...importJobState
541
- }, options);
298
+ return operator.findOne({ ...importJobState }, options);
542
299
  }
543
-
544
- // importJobState and queueItemState
545
300
  if (importJobState && queueItemState) {
546
301
  logger.silly(`Checking DB ${collection} for ${queueItemState} and ${JSON.stringify(importJobState)}`);
547
- //debug(`Checking DB ${collection} for ${queueItemState} and ${JSON.stringify(importJobState)}`);
548
- return operator.findOne({
549
- ...cleanQueueItemState,
550
- ...importJobState
551
- }, options);
302
+ return operator.findOne({ ...cleanQueueItemState, ...importJobState }, options);
552
303
  }
553
304
  logger.debug(`getOne not working!`);
554
- throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, 'Missing parameters, cannot get queueItem');
305
+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, "Missing parameters, cannot get queueItem");
555
306
  } catch (error) {
556
- const errorMessage = error.payload || error.message || '';
557
- (0, _utils.logError)(error);
558
- throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, `Mongo errored: ${errorMessage}`);
307
+ const errorMessage = error.payload || error.message || "";
308
+ logError(error);
309
+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, `Mongo errored: ${errorMessage}`);
559
310
  }
560
311
  }
561
312
  function getStream(correlationId) {
562
313
  logger.info(`Forming stream from mongo for ${correlationId} in ${collection}`);
563
- const clean = (0, _mongoSanitize.default)(correlationId);
314
+ const clean = sanitize(correlationId);
564
315
  try {
565
- // Return content stream
566
316
  return gridFSBucket.openDownloadStreamByName(clean);
567
317
  } catch (error) {
568
- // TEST-COVERAGE: this error is not (currently) tested
569
- const errorMessage = error.payload || error.message || '';
570
- (0, _utils.logError)(error);
571
- throw new _melindaCommons.Error(_httpStatus.default.INTERNAL_SERVER_ERROR, `Mongo errored: ${errorMessage}`);
318
+ const errorMessage = error.payload || error.message || "";
319
+ logError(error);
320
+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, `Mongo errored: ${errorMessage}`);
572
321
  }
573
322
  }
574
- async function pushIds({
575
- correlationId,
576
- handledIds,
577
- rejectedIds
578
- }) {
323
+ async function pushIds({ correlationId, handledIds, rejectedIds }) {
579
324
  logger.verbose(`Push ids (${handledIds.length}) and rejectedIds (${rejectedIds.length}) ${correlationId} to ${collection}`);
580
325
  logger.debug(`ids (${handledIds.length}): ${JSON.stringify(handledIds)}, rejectedIds ${rejectedIds.length}: ${JSON.stringify(rejectedIds)}`);
581
- const clean = (0, _mongoSanitize.default)(correlationId);
326
+ const clean = sanitize(correlationId);
582
327
  await operator.updateOne({
583
328
  correlationId: clean
584
329
  }, {
585
330
  $set: {
586
- modificationTime: (0, _moment.default)().toDate()
331
+ modificationTime: moment().toDate()
587
332
  },
588
333
  $push: {
589
- handledIds: {
590
- $each: handledIds
591
- },
592
- rejectedIds: {
593
- $each: rejectedIds
594
- }
334
+ handledIds: { $each: handledIds },
335
+ rejectedIds: { $each: rejectedIds }
595
336
  }
596
337
  });
597
338
  }
598
- async function pushMessages({
599
- correlationId,
600
- messages,
601
- messageField = 'messages'
602
- }) {
339
+ async function pushMessages({ correlationId, messages, messageField = "messages" }) {
603
340
  logger.verbose(`Push messages (${messages.length}) to ${messageField} ${correlationId} to ${collection}`);
604
341
  logger.silly(`Messages (${messages.length}): ${JSON.stringify(messages)}}`);
605
- const clean = (0, _mongoSanitize.default)(correlationId);
606
- const cleanMessageField = (0, _mongoSanitize.default)(messageField);
342
+ const clean = sanitize(correlationId);
343
+ const cleanMessageField = sanitize(messageField);
607
344
  debug(`${messageField} -> ${cleanMessageField}`);
608
345
  await operator.updateOne({
609
346
  correlationId: clean
610
347
  }, {
611
348
  $set: {
612
- modificationTime: (0, _moment.default)().toDate()
349
+ modificationTime: moment().toDate()
613
350
  },
614
351
  $push: {
615
- [cleanMessageField]: {
616
- $each: messages
617
- }
352
+ [cleanMessageField]: { $each: messages }
618
353
  }
619
354
  });
620
355
  }
621
- function setState({
622
- correlationId,
623
- state,
624
- errorMessage = undefined,
625
- errorStatus = undefined
626
- }) {
627
- const errorString = errorMessage || errorStatus ? `, Error message: '${JSON.stringify(errorMessage) || ''}', Error status: '${errorStatus || ''}'` : '';
356
+ function setState({ correlationId, state, errorMessage = void 0, errorStatus = void 0 }) {
357
+ const errorString = errorMessage || errorStatus ? `, Error message: '${JSON.stringify(errorMessage) || ""}', Error status: '${errorStatus || ""}'` : "";
628
358
  logger.info(`Setting queue-item state ${state} for ${correlationId}${errorString} to ${collection}`);
629
- const stateInQueueItemStates = Object.values(_constants.QUEUE_ITEM_STATE).indexOf(state) > -1;
630
- const stateInQueueItemStatesValidator = Object.values(_constants.QUEUE_ITEM_STATE.VALIDATOR).indexOf(state) > -1;
631
- const stateInQueueItemStatesImporter = Object.values(_constants.QUEUE_ITEM_STATE.IMPORTER).indexOf(state) > -1;
359
+ const stateInQueueItemStates = Object.values(QUEUE_ITEM_STATE).indexOf(state) > -1;
360
+ const stateInQueueItemStatesValidator = Object.values(QUEUE_ITEM_STATE.VALIDATOR).indexOf(state) > -1;
361
+ const stateInQueueItemStatesImporter = Object.values(QUEUE_ITEM_STATE.IMPORTER).indexOf(state) > -1;
632
362
  if (!stateInQueueItemStates && !stateInQueueItemStatesValidator && !stateInQueueItemStatesImporter) {
633
363
  debug(`Trying to set invalid state ${state}`);
634
- throw new _melindaCommons.Error(_httpStatus.default.BAD_REQUEST, 'Trying to set invalid state');
364
+ throw new ApiError(httpStatus.BAD_REQUEST, "Trying to set invalid state");
635
365
  }
636
- const clean = (0, _mongoSanitize.default)(correlationId);
366
+ const clean = sanitize(correlationId);
637
367
  const updateValues = {
638
368
  queueItemState: state,
639
- modificationTime: (0, _moment.default)().toDate(),
369
+ modificationTime: moment().toDate(),
640
370
  errorMessage,
641
371
  errorStatus
642
372
  };
643
-
644
- // Do not update value that are undefined
645
- // eslint-disable-next-line functional/immutable-data
646
- Object.keys(updateValues).forEach(key => updateValues[key] === undefined && delete updateValues[key]);
647
- return operator.findOneAndUpdate({
648
- correlationId: clean
649
- }, {
650
- $set: updateValues
651
- }, {
652
- projection: {
653
- _id: 0
654
- },
655
- returnDocument: 'after'
656
- });
373
+ Object.keys(updateValues).forEach((key) => updateValues[key] === void 0 && delete updateValues[key]);
374
+ return operator.findOneAndUpdate(
375
+ { correlationId: clean },
376
+ { $set: updateValues },
377
+ { projection: { _id: 0 }, returnDocument: "after" }
378
+ );
657
379
  }
658
- function setImportJobState({
659
- correlationId,
660
- operation,
661
- importJobState
662
- }) {
663
- // should this also get importJobState as previously created object? {}
380
+ function setImportJobState({ correlationId, operation, importJobState }) {
664
381
  logger.info(`Setting queue-item importJobState: {${operation}: ${importJobState}} for ${correlationId}`);
665
382
  debug(`Setting queue-item importJobState: {${operation}: ${importJobState}} for ${correlationId}`);
666
- const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId);
667
- const cleanImportJobState = (0, _mongoSanitize.default)(importJobState);
668
- if (!(operation in _constants.OPERATIONS)) {
669
- debug(`Error: ${operation} is not in ${JSON.stringify(_constants.OPERATIONS)}`);
670
- throw new _melindaCommons.Error(_httpStatus.default.BAD_REQUEST, 'Invalid operation for import job state');
383
+ const cleanCorrelationId = sanitize(correlationId);
384
+ const cleanImportJobState = sanitize(importJobState);
385
+ if (!(operation in OPERATIONS)) {
386
+ debug(`Error: ${operation} is not in ${JSON.stringify(OPERATIONS)}`);
387
+ throw new ApiError(httpStatus.BAD_REQUEST, "Invalid operation for import job state");
671
388
  }
672
- if (!(cleanImportJobState in _constants.IMPORT_JOB_STATE)) {
673
- debug(`Error: ${cleanImportJobState} is not in ${JSON.stringify(_constants.IMPORT_JOB_STATE)}`);
674
- throw new _melindaCommons.Error(_httpStatus.default.BAD_REQUEST, 'Invalid import job state');
389
+ if (!(cleanImportJobState in IMPORT_JOB_STATE)) {
390
+ debug(`Error: ${cleanImportJobState} is not in ${JSON.stringify(IMPORT_JOB_STATE)}`);
391
+ throw new ApiError(httpStatus.BAD_REQUEST, "Invalid import job state");
675
392
  }
676
393
  const newJobState = getNewJobState(operation, cleanImportJobState);
677
- function getNewJobState(operation, cleanImportJobState) {
678
- if (operation === _constants.OPERATIONS.CREATE) {
679
- return {
680
- 'importJobState.CREATE': cleanImportJobState
681
- };
394
+ function getNewJobState(operation2, cleanImportJobState2) {
395
+ if (operation2 === OPERATIONS.CREATE) {
396
+ return { "importJobState.CREATE": cleanImportJobState2 };
682
397
  }
683
- if (operation === _constants.OPERATIONS.UPDATE) {
684
- return {
685
- 'importJobState.UPDATE': cleanImportJobState
686
- };
398
+ if (operation2 === OPERATIONS.UPDATE) {
399
+ return { "importJobState.UPDATE": cleanImportJobState2 };
687
400
  }
688
- if (operation === _constants.OPERATIONS.FIX) {
689
- return {
690
- 'importJobState.FIX': cleanImportJobState
691
- };
401
+ if (operation2 === OPERATIONS.FIX) {
402
+ return { "importJobState.FIX": cleanImportJobState2 };
692
403
  }
693
- // istanbul ignore next
694
- // Ignoring for coverage - we error this already
695
- throw new _melindaCommons.Error('400', 'Invalid operation for import job state');
404
+ throw new ApiError("400", "Invalid operation for import job state");
696
405
  }
697
406
  return operator.findOneAndUpdate({
698
407
  correlationId: cleanCorrelationId
699
408
  }, {
700
409
  $set: {
701
410
  ...newJobState,
702
- modificationTime: (0, _moment.default)().toDate()
411
+ modificationTime: moment().toDate()
703
412
  }
704
- }, {
705
- projection: {
706
- _id: 0
707
- },
708
- returnDocument: 'after'
709
- });
413
+ }, { projection: { _id: 0 }, returnDocument: "after" });
710
414
  }
711
- async function setOperation({
712
- correlationId,
713
- operation
714
- }) {
415
+ async function setOperation({ correlationId, operation }) {
715
416
  const newOperation = operation;
716
- const {
717
- operation: oldOperation
718
- } = await operator.findOne({
719
- correlationId
720
- });
417
+ const { operation: oldOperation } = await operator.findOne({ correlationId });
721
418
  logger.info(`Setting queue-item operation from ${oldOperation} to ${newOperation} for ${correlationId} to ${collection}`);
722
- const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId);
723
- const cleanNewOperation = (0, _mongoSanitize.default)(newOperation);
419
+ const cleanCorrelationId = sanitize(correlationId);
420
+ const cleanNewOperation = sanitize(newOperation);
724
421
  const result = await operator.findOneAndUpdate({
725
422
  correlationId: cleanCorrelationId
726
423
  }, {
727
424
  $set: {
728
425
  operation: cleanNewOperation,
729
- modificationTime: (0, _moment.default)().toDate()
426
+ modificationTime: moment().toDate()
730
427
  }
731
- }, {
732
- projection: {
733
- _id: 0
734
- },
735
- returnDocument: 'after'
736
- });
428
+ }, { projection: { _id: 0 }, returnDocument: "after" });
737
429
  debugDev(`${JSON.stringify(result)}`);
738
430
  return result.ok || result;
739
- // logger.debug(JSON.stringify(result));
740
431
  }
741
- async function setOperations({
742
- correlationId,
743
- addOperation,
744
- removeOperation = undefined
745
- }) {
746
- const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId);
747
- const queueItem = await operator.findOne({
748
- correlationId: cleanCorrelationId
749
- });
432
+ async function setOperations({ correlationId, addOperation, removeOperation = void 0 }) {
433
+ const cleanCorrelationId = sanitize(correlationId);
434
+ const queueItem = await operator.findOne({ correlationId: cleanCorrelationId });
750
435
  logger.silly(`We found a queueItem: ${JSON.stringify(queueItem)}`);
751
436
  const oldOperations = queueItem.operations;
752
437
  logger.info(`Setting queue-item operations from ${JSON.stringify(oldOperations)} by adding ${addOperation} and removing ${removeOperation} for ${correlationId} to ${collection}`);
753
- const operationsAfterRemove = oldOperations.filter(operation => operation !== removeOperation);
438
+ const operationsAfterRemove = oldOperations.filter((operation) => operation !== removeOperation);
754
439
  const operationsAfterRemoveAndAdd = operationsAfterRemove.includes(addOperation) ? operationsAfterRemove : [...operationsAfterRemove, addOperation];
755
440
  logger.silly(`operationsAfterRemove: ${operationsAfterRemove}`);
756
441
  logger.silly(`operationAfterRemoveAndAdd: ${operationsAfterRemoveAndAdd}`);
@@ -759,64 +444,43 @@ async function _default(MONGO_URI, collection, db = 'rest-api') {
759
444
  }, {
760
445
  $set: {
761
446
  operations: operationsAfterRemoveAndAdd,
762
- modificationTime: (0, _moment.default)().toDate()
447
+ modificationTime: moment().toDate()
763
448
  }
764
- }, {
765
- projection: {
766
- _id: 0
767
- },
768
- returnDocument: 'after'
769
- });
449
+ }, { projection: { _id: 0 }, returnDocument: "after" });
770
450
  debugDev(`${JSON.stringify(result)}`);
771
451
  return result.ok || result;
772
- // logger.debug(JSON.stringify(result));
773
452
  }
774
- async function addBlobSize({
775
- correlationId
776
- }) {
777
- const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId);
453
+ async function addBlobSize({ correlationId }) {
454
+ const cleanCorrelationId = sanitize(correlationId);
778
455
  const result = await operator.findOneAndUpdate({
779
456
  correlationId: cleanCorrelationId,
780
- queueItemState: _constants.QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS
457
+ queueItemState: QUEUE_ITEM_STATE.VALIDATOR.WAITING_FOR_RECORDS
781
458
  }, {
782
459
  $inc: {
783
460
  blobSize: 1
784
461
  },
785
462
  $set: {
786
- modificationTime: (0, _moment.default)().toDate()
463
+ modificationTime: moment().toDate()
787
464
  }
788
- }, {
789
- projection: {
790
- _id: 0
791
- },
792
- returnDocument: 'after'
793
- });
465
+ }, { projection: { _id: 0 }, returnDocument: "after" });
794
466
  logger.verbose(`AddBlobSizeResult in mongo: ${JSON.stringify(result)}`);
795
467
  debugDev(`${JSON.stringify(result)}`);
796
468
  return result;
797
469
  }
798
- async function setBlobSize({
799
- correlationId,
800
- blobSize
801
- }) {
802
- const cleanCorrelationId = (0, _mongoSanitize.default)(correlationId);
803
- const cleanBlobSize = (0, _mongoSanitize.default)(blobSize);
470
+ async function setBlobSize({ correlationId, blobSize }) {
471
+ const cleanCorrelationId = sanitize(correlationId);
472
+ const cleanBlobSize = sanitize(blobSize);
804
473
  const result = await operator.findOneAndUpdate({
805
474
  correlationId: cleanCorrelationId
806
475
  }, {
807
476
  $set: {
808
477
  blobSize: cleanBlobSize,
809
- modificationTime: (0, _moment.default)().toDate()
478
+ modificationTime: moment().toDate()
810
479
  }
811
- }, {
812
- projection: {
813
- _id: 0
814
- },
815
- returnDocument: 'after'
816
- });
480
+ }, { projection: { _id: 0 }, returnDocument: "after" });
817
481
  logger.verbose(`SetBlobSizeResult in mongo: ${JSON.stringify(result)}`);
818
482
  debugDev(`${JSON.stringify(result)}`);
819
483
  return result;
820
484
  }
821
485
  }
822
- //# sourceMappingURL=mongo.js.map
486
+ //# sourceMappingURL=mongo.js.map