@natlibfi/melinda-rest-api-commons 2.3.1-alpha.3 → 2.3.1-alpha.5

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/mongoLog.js CHANGED
@@ -77,7 +77,13 @@ async function _default(MONGO_URI) {
77
77
  const result = await db.collection(collection).insertOne(newLogItem);
78
78
 
79
79
  if (result.acknowledged) {
80
- logger.info(`*** New ${logItem.logItemType} added for ${logItem.correlationId} items ${logItem.blobSequenceStart}-${logItem.blobSequenceEnd}. ***`);
80
+ const {
81
+ blobSequence,
82
+ blobSequenceStart,
83
+ blobSequenceEnd
84
+ } = logItem;
85
+ const itemString = blobSequenceStart && blobSequenceEnd ? `${blobSequenceStart} - ${blobSequenceEnd}` : `${blobSequence}`;
86
+ logger.info(`*** New ${logItem.logItemType} added for ${logItem.correlationId} items ${itemString}. ***`);
81
87
  return;
82
88
  }
83
89
 
@@ -99,7 +105,7 @@ async function _default(MONGO_URI) {
99
105
  .find(rest).sort({
100
106
  blobSequence: 1
101
107
  }).skip(parseInt(skip, 10)).limit(parseInt(limit, 10)).toArray();
102
- logger.debug(result);
108
+ logger.debug(`Query result: ${result}`);
103
109
  logger.debug(`Query result: ${result.length > 0 ? `Found ${result.length} log items! (skip: ${skip} limit: ${limit})` : 'Not found!'}`);
104
110
  return result;
105
111
  }
@@ -1 +1 @@
1
- {"version":3,"file":"mongoLog.js","names":["MONGO_URI","logger","createLogger","client","MongoClient","connect","useNewUrlParser","useUnifiedTopology","db","collection","addLogItem","query","queryById","getListOfLogs","protect","remove","logItem","time","moment","toDate","newLogItem","creationTime","protected","result","insertOne","acknowledged","info","logItemType","correlationId","blobSequenceStart","blobSequenceEnd","ApiError","httpStatus","INTERNAL_SERVER_ERROR","error","logError","params","debug","JSON","stringify","limit","skip","rest","find","sort","blobSequence","parseInt","toArray","length","correlationIdString","distinct","status","OK","NOT_FOUND","payload","cleanCorrelationId","sanitize","cleanBlobSequence","filter","updateMany","$set","modificationTime","$not","modifiedCount","err","message","force","clean","$ne","deleteMany","deletedCount"],"sources":["../src/mongoLog.js"],"sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Shared modules for microservices of Melinda rest api batch import system\n*\n* Copyright (C) 2020-2022 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-rest-api-commons\n*\n* melinda-rest-api-commons program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-rest-api-commons is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport {MongoClient} from 'mongodb';\nimport {createLogger} from '@natlibfi/melinda-backend-commons';\nimport {Error as ApiError} from '@natlibfi/melinda-commons';\nimport {logError} from './utils.js';\nimport moment from 'moment';\nimport httpStatus from 'http-status';\nimport sanitize from 'mongo-sanitize';\n\nexport default async function (MONGO_URI) {\n const logger = createLogger();\n\n // Connect to mongo (MONGO)\n const client = await MongoClient.connect(MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true});\n const db = client.db('rest-api');\n const collection = 'logs';\n return {addLogItem, query, queryById, getListOfLogs, protect, remove};\n\n async function addLogItem(logItem) {\n const time = moment().toDate();\n const newLogItem = {\n ...logItem,\n creationTime: time,\n protected: false\n };\n try {\n const result = await db.collection(collection).insertOne(newLogItem);\n if (result.acknowledged) {\n logger.info(`*** New ${logItem.logItemType} added for ${logItem.correlationId} items ${logItem.blobSequenceStart}-${logItem.blobSequenceEnd}. ***`);\n return;\n }\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);\n } catch (error) {\n logError(error);\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);\n }\n }\n\n async function query(params) {\n logger.debug(`Query params: ${JSON.stringify(params)}`);\n const {limit = 5, skip = 0, ...rest} = params;\n const result = await db.collection(collection) // eslint-disable-line functional/immutable-data\n .find(rest)\n .sort({blobSequence: 1})\n .skip(parseInt(skip, 10))\n .limit(parseInt(limit, 10))\n .toArray();\n logger.debug(result);\n logger.debug(`Query result: ${result.length > 0 ? `Found ${result.length} log items! (skip: ${skip} limit: ${limit})` : 'Not found!'}`);\n return result;\n }\n\n async function queryById(correlationIdString, skip = 0, limit = 1) {\n logger.debug(`QueryById: ${correlationIdString}`);\n const result = await db.collection(collection) // eslint-disable-line functional/immutable-data\n .find({correlationId: correlationIdString})\n .sort({blobSequence: 1})\n .skip(parseInt(skip, 10))\n .limit(parseInt(limit, 10))\n .toArray();\n logger.debug(`Query result: ${result.length > 0 ? `Found ${result.length} log items!` : 'Not found!'}`);\n return result;\n }\n\n async function getListOfLogs(logItemType = 'MERGE_LOG') {\n const result = await db.collection(collection) // eslint-disable-line functional/immutable-data\n .distinct('correlationId', {logItemType});\n logger.debug(`Query result: ${result.length > 0 ? `Found ${result.length} log items!` : 'Not found!'}`);\n return {status: result.length > 0 ? httpStatus.OK : httpStatus.NOT_FOUND, payload: result.length > 0 ? result : 'No logs found'};\n }\n\n async function protect(correlationId, blobSequence) {\n logger.info(`Removing from Mongo (${collection}) correlationId: ${correlationId}, blobSequence: ${blobSequence}`);\n const cleanCorrelationId = sanitize(correlationId);\n const cleanBlobSequence = sanitize(blobSequence);\n const filter = blobSequence ? {correlationId: cleanCorrelationId, blobSequence: cleanBlobSequence} : {correlationId: cleanCorrelationId};\n\n try {\n const result = await db.collection(collection).updateMany(\n filter,\n {\n $set: {\n modificationTime: moment().toDate(),\n protect: {$not: '$protect'}\n }\n }\n );\n return {status: result.modifiedCount > 0 ? httpStatus.OK : httpStatus.NOT_FOUND, payload: result.modifiedCount > 0 ? result : 'No logs found'};\n } catch (err) {\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, err.message);\n }\n }\n\n async function remove(correlationId, force = false) {\n logger.info(`Removing from Mongo (${collection}) correlationId: ${correlationId}`);\n const clean = sanitize(correlationId);\n const filter = force ? {correlationId: clean} : {correlationId: clean, protected: {$ne: true}};\n\n try {\n const result = await db.collection(collection).deleteMany(filter);\n return {status: result.deletedCount > 0 ? httpStatus.OK : httpStatus.NOT_FOUND, payload: result.deletedCount > 0 ? result : 'No logs found'};\n } catch (err) {\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, err.message);\n }\n }\n}\n"],"mappings":";;;;;;;AA4BA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;AAlCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAUe,wBAAgBA,SAAhB,EAA2B;EACxC,MAAMC,MAAM,GAAG,IAAAC,mCAAA,GAAf,CADwC,CAGxC;;EACA,MAAMC,MAAM,GAAG,MAAMC,oBAAA,CAAYC,OAAZ,CAAoBL,SAApB,EAA+B;IAACM,eAAe,EAAE,IAAlB;IAAwBC,kBAAkB,EAAE;EAA5C,CAA/B,CAArB;EACA,MAAMC,EAAE,GAAGL,MAAM,CAACK,EAAP,CAAU,UAAV,CAAX;EACA,MAAMC,UAAU,GAAG,MAAnB;EACA,OAAO;IAACC,UAAD;IAAaC,KAAb;IAAoBC,SAApB;IAA+BC,aAA/B;IAA8CC,OAA9C;IAAuDC;EAAvD,CAAP;;EAEA,eAAeL,UAAf,CAA0BM,OAA1B,EAAmC;IACjC,MAAMC,IAAI,GAAG,IAAAC,eAAA,IAASC,MAAT,EAAb;IACA,MAAMC,UAAU,GAAG,EACjB,GAAGJ,OADc;MAEjBK,YAAY,EAAEJ,IAFG;MAGjBK,SAAS,EAAE;IAHM,CAAnB;;IAKA,IAAI;MACF,MAAMC,M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GQ,KAAK,GAAG;MAACtC,aAAa,EAAEuC;IAAhB,CAAH,GAA4B;MAACvC,aAAa,EAAEuC,KAAhB;MAAuB7C,SAAS,EAAE;QAAC8C,GAAG,EAAE;MAAN;IAAlC,CAAhD;;IAEA,IAAI;MACF,MAAM7C,MAAM,GAAG,MAAMf,EAAE,CAACC,UAAH,CAAcA,UAAd,EAA0B4D,UAA1B,CAAqCX,MAArC,CAArB;MACA,OAAO;QAACP,MAAM,EAAE5B,MAAM,CAAC+C,YAAP,GAAsB,CAAtB,GAA0BtC,mBAAA,CAAWoB,EAArC,GAA0CpB,mBAAA,CAAWqB,SAA9D;QAAyEC,OAAO,EAAE/B,MAAM,CAAC+C,YAAP,GAAsB,CAAtB,GAA0B/C,MAA1B,GAAmC;MAArH,CAAP;IACD,CAHD,CAGE,OAAOyC,GAAP,EAAY;MACZ,MAAM,IAAIjC,qBAAJ,CAAaC,mBAAA,CAAWC,qBAAxB,EAA+C+B,GAAG,CAACC,OAAnD,CAAN;IACD;EACF;AACF"}
1
+ {"version":3,"file":"mongoLog.js","names":["MONGO_URI","logger","createLogger","client","MongoClient","connect","useNewUrlParser","useUnifiedTopology","db","collection","addLogItem","query","queryById","getListOfLogs","protect","remove","logItem","time","moment","toDate","newLogItem","creationTime","protected","result","insertOne","acknowledged","blobSequence","blobSequenceStart","blobSequenceEnd","itemString","info","logItemType","correlationId","ApiError","httpStatus","INTERNAL_SERVER_ERROR","error","logError","params","debug","JSON","stringify","limit","skip","rest","find","sort","parseInt","toArray","length","correlationIdString","distinct","status","OK","NOT_FOUND","payload","cleanCorrelationId","sanitize","cleanBlobSequence","filter","updateMany","$set","modificationTime","$not","modifiedCount","err","message","force","clean","$ne","deleteMany","deletedCount"],"sources":["../src/mongoLog.js"],"sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Shared modules for microservices of Melinda rest api batch import system\n*\n* Copyright (C) 2020-2022 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-rest-api-commons\n*\n* melinda-rest-api-commons program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-rest-api-commons is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport {MongoClient} from 'mongodb';\nimport {createLogger} from '@natlibfi/melinda-backend-commons';\nimport {Error as ApiError} from '@natlibfi/melinda-commons';\nimport {logError} from './utils.js';\nimport moment from 'moment';\nimport httpStatus from 'http-status';\nimport sanitize from 'mongo-sanitize';\n\nexport default async function (MONGO_URI) {\n const logger = createLogger();\n\n // Connect to mongo (MONGO)\n const client = await MongoClient.connect(MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true});\n const db = client.db('rest-api');\n const collection = 'logs';\n return {addLogItem, query, queryById, getListOfLogs, protect, remove};\n\n async function addLogItem(logItem) {\n const time = moment().toDate();\n const newLogItem = {\n ...logItem,\n creationTime: time,\n protected: false\n };\n try {\n const result = await db.collection(collection).insertOne(newLogItem);\n if (result.acknowledged) {\n const {blobSequence, blobSequenceStart, blobSequenceEnd} = logItem;\n const itemString = blobSequenceStart && blobSequenceEnd ? `${blobSequenceStart} - ${blobSequenceEnd}` : `${blobSequence}`;\n logger.info(`*** New ${logItem.logItemType} added for ${logItem.correlationId} items ${itemString}. ***`);\n return;\n }\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);\n } catch (error) {\n logError(error);\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR);\n }\n }\n\n async function query(params) {\n logger.debug(`Query params: ${JSON.stringify(params)}`);\n const {limit = 5, skip = 0, ...rest} = params;\n const result = await db.collection(collection) // eslint-disable-line functional/immutable-data\n .find(rest)\n .sort({blobSequence: 1})\n .skip(parseInt(skip, 10))\n .limit(parseInt(limit, 10))\n .toArray();\n logger.debug(`Query result: ${result}`);\n logger.debug(`Query result: ${result.length > 0 ? `Found ${result.length} log items! (skip: ${skip} limit: ${limit})` : 'Not found!'}`);\n return result;\n }\n\n async function queryById(correlationIdString, skip = 0, limit = 1) {\n logger.debug(`QueryById: ${correlationIdString}`);\n const result = await db.collection(collection) // eslint-disable-line functional/immutable-data\n .find({correlationId: correlationIdString})\n .sort({blobSequence: 1})\n .skip(parseInt(skip, 10))\n .limit(parseInt(limit, 10))\n .toArray();\n logger.debug(`Query result: ${result.length > 0 ? `Found ${result.length} log items!` : 'Not found!'}`);\n return result;\n }\n\n async function getListOfLogs(logItemType = 'MERGE_LOG') {\n const result = await db.collection(collection) // eslint-disable-line functional/immutable-data\n .distinct('correlationId', {logItemType});\n logger.debug(`Query result: ${result.length > 0 ? `Found ${result.length} log items!` : 'Not found!'}`);\n return {status: result.length > 0 ? httpStatus.OK : httpStatus.NOT_FOUND, payload: result.length > 0 ? result : 'No logs found'};\n }\n\n async function protect(correlationId, blobSequence) {\n logger.info(`Removing from Mongo (${collection}) correlationId: ${correlationId}, blobSequence: ${blobSequence}`);\n const cleanCorrelationId = sanitize(correlationId);\n const cleanBlobSequence = sanitize(blobSequence);\n const filter = blobSequence ? {correlationId: cleanCorrelationId, blobSequence: cleanBlobSequence} : {correlationId: cleanCorrelationId};\n\n try {\n const result = await db.collection(collection).updateMany(\n filter,\n {\n $set: {\n modificationTime: moment().toDate(),\n protect: {$not: '$protect'}\n }\n }\n );\n return {status: result.modifiedCount > 0 ? httpStatus.OK : httpStatus.NOT_FOUND, payload: result.modifiedCount > 0 ? result : 'No logs found'};\n } catch (err) {\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, err.message);\n }\n }\n\n async function remove(correlationId, force = false) {\n logger.info(`Removing from Mongo (${collection}) correlationId: ${correlationId}`);\n const clean = sanitize(correlationId);\n const filter = force ? {correlationId: clean} : {correlationId: clean, protected: {$ne: true}};\n\n try {\n const result = await db.collection(collection).deleteMany(filter);\n return {status: result.deletedCount > 0 ? httpStatus.OK : httpStatus.NOT_FOUND, payload: result.deletedCount > 0 ? result : 'No logs found'};\n } catch (err) {\n throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, err.message);\n }\n }\n}\n"],"mappings":";;;;;;;AA4BA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;AAlCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAUe,wBAAgBA,SAAhB,EAA2B;EACxC,MAAMC,MAAM,GAAG,IAAAC,mCAAA,GAAf,CADwC,CAGxC;;EACA,MAAMC,MAAM,GAAG,MAAMC,oBAAA,CAAYC,OAAZ,CAAoBL,SAApB,EAA+B;IAACM,eAAe,EAAE,IAAlB;IAAwBC,kBAAkB,EAAE;EAA5C,CAA/B,CAArB;EACA,MAAMC,EAAE,GAAGL,MAAM,CAACK,EAAP,CAAU,UAAV,CAAX;EACA,MAAMC,UAAU,GAAG,MAAnB;EACA,OAAO;IAACC,UAAD;IAAaC,KAAb;IAAoBC,SAApB;IAA+BC,aAA/B;IAA8CC,OAA9C;IAAuDC;EAAvD,CAAP;;EAEA,eAAeL,UAAf,CAA0BM,OAA1B,EAAmC;IACjC,MAAMC,IAAI,GAAG,IAAAC,eAAA,IAASC,MAAT,EAAb;IACA,MAAMC,UAAU,GAAG,EACjB,GAAGJ,OADc;MAEjBK,YAAY,EAAEJ,IAFG;MAGjBK,SAAS,EAAE;IAHM,CAAnB;;IAKA,IAAI;MACF,MAAMC,MAAM,GAAG,MAAMf,EAAE,CAACC,UAAH,CAAcA,UAAd,EAA0Be,SAA1B,CAAoCJ,UAApC,CAArB;;MACA,IAAIG,MAAM,CAACE,YAAX,EAA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,KAAK,GAAG,IAAAX,sBAAA,EAASzB,aAAT,CAAd;IACA,MAAM2B,MAAM,GAAGQ,KAAK,GAAG;MAACnC,aAAa,EAAEoC;IAAhB,CAAH,GAA4B;MAACpC,aAAa,EAAEoC,KAAhB;MAAuB9C,SAAS,EAAE;QAAC+C,GAAG,EAAE;MAAN;IAAlC,CAAhD;;IAEA,IAAI;MACF,MAAM9C,MAAM,GAAG,MAAMf,EAAE,CAACC,UAAH,CAAcA,UAAd,EAA0B6D,UAA1B,CAAqCX,MAArC,CAArB;MACA,OAAO;QAACP,MAAM,EAAE7B,MAAM,CAACgD,YAAP,GAAsB,CAAtB,GAA0BrC,mBAAA,CAAWmB,EAArC,GAA0CnB,mBAAA,CAAWoB,SAA9D;QAAyEC,OAAO,EAAEhC,MAAM,CAACgD,YAAP,GAAsB,CAAtB,GAA0BhD,MAA1B,GAAmC;MAArH,CAAP;IACD,CAHD,CAGE,OAAO0C,GAAP,EAAY;MACZ,MAAM,IAAIhC,qBAAJ,CAAaC,mBAAA,CAAWC,qBAAxB,EAA+C8B,GAAG,CAACC,OAAnD,CAAN;IACD;EACF;AACF"}
package/dist/utils.js CHANGED
@@ -105,18 +105,22 @@ function getRecordResponseStatusAndMessage(responseStatus, responsePayload, id)
105
105
  logger.debug(`Response status name: ${responseStatusName}`);
106
106
  const message = getMessageFromResponsePayload(responsePayload);
107
107
  const ids = responsePayload.ids || [];
108
- logger.debug(`Response message: ${message}`); // Non-http statuses
108
+ logger.debug(`Response message: ${message}`); // We map responseStatus here for a wider recordStatus and more detailed detailedRecordStatus
109
+ // recordStatus corresponds to RECORD_IMPORT_STATEs used in https://github.com/NatLibFi/melinda-record-import-commons-js
110
+ // Non-http statuses
109
111
 
110
112
  if (['UPDATED', 'CREATED', 'INVALID', 'ERROR', 'SKIPPED'].includes(responseStatus)) {
111
113
  return {
112
114
  recordStatus: responseStatus,
115
+ detailedRecordStatus: responseStatus,
113
116
  message
114
117
  };
115
118
  }
116
119
 
117
120
  if (['UNKNOWN'].includes(responseStatus)) {
118
121
  return {
119
- recordStatus: responseStatus,
122
+ recordStatus: 'ERROR',
123
+ detailedRecordStatus: responseStatus,
120
124
  message,
121
125
  ids
122
126
  };
@@ -127,6 +131,7 @@ function getRecordResponseStatusAndMessage(responseStatus, responsePayload, id)
127
131
  if (/^Duplicates in database/u.test(message)) {
128
132
  return {
129
133
  recordStatus: 'DUPLICATE',
134
+ detailedRecordStatus: 'DUPLICATE',
130
135
  message,
131
136
  ids
132
137
  };
@@ -134,7 +139,8 @@ function getRecordResponseStatusAndMessage(responseStatus, responsePayload, id)
134
139
 
135
140
  if (/^MatchValidation for all/u.test(message)) {
136
141
  return {
137
- recordStatus: 'CONFLICT',
142
+ recordStatus: 'ERROR',
143
+ detailedRecordStatus: 'CONFLICT',
138
144
  message,
139
145
  ids
140
146
  };
@@ -143,14 +149,16 @@ function getRecordResponseStatusAndMessage(responseStatus, responsePayload, id)
143
149
 
144
150
  if (ids.length > 1 || ids[0] !== id) {
145
151
  return {
146
- recordStatus: 'CONFLICT',
152
+ recordStatus: 'ERROR',
153
+ detailedRecordStatus: 'CONFLICT',
147
154
  message,
148
155
  ids
149
156
  };
150
157
  }
151
158
 
152
159
  return {
153
- recordStatus: 'CONFLICT',
160
+ recordStatus: 'ERROR',
161
+ detailedRecordStatus: 'CONFLICT',
154
162
  message
155
163
  };
156
164
  }
@@ -158,21 +166,24 @@ function getRecordResponseStatusAndMessage(responseStatus, responsePayload, id)
158
166
  if ([_httpStatus.default.UNPROCESSABLE_ENTITY, 'UNPROCESSABLE_ENTITY'].includes(responseStatus)) {
159
167
  if (ids.length > 1 || ids[0] !== id) {
160
168
  return {
161
- recordStatus: 'UNPROCESSABLE_ENTITY',
169
+ recordStatus: 'INVALID',
170
+ detailedRecordStatus: 'UNPROCESSABLE_ENTITY',
162
171
  message,
163
172
  ids
164
173
  };
165
174
  }
166
175
 
167
176
  return {
168
- recordStatus: 'UNPROCESSABLE_ENTITY',
177
+ recordStatus: 'INVALID',
178
+ detailedRecordStatus: 'UNPROCESSABLE_ENTITY',
169
179
  message
170
180
  };
171
181
  }
172
182
 
173
183
  if ([_httpStatus.default.NOT_FOUND, 'NOT_FOUND'].includes(responseStatus)) {
174
184
  return {
175
- recordStatus: 'NOT_FOUND',
185
+ recordStatus: 'ERROR',
186
+ detailedRecordStatus: 'NOT_FOUND',
176
187
  message
177
188
  };
178
189
  } // Otherwise
@@ -180,6 +191,7 @@ function getRecordResponseStatusAndMessage(responseStatus, responsePayload, id)
180
191
 
181
192
  return {
182
193
  recordStatus: 'ERROR',
194
+ detailedRecordStatus: responseStatus,
183
195
  message
184
196
  };
185
197
  }
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":["logger","createLogger","logError","err","ApiError","error","JSON","stringify","stack","undefined","createImportJobState","operation","state","queryImportJobState","IMPORT_JOB_STATE","Error","OPERATIONS","importJobStateWithOperation","importJobStateForQuery","createRecordResponseItem","responsePayload","responseStatus","recordMetadata","id","recordResponseStatusAndMessage","getRecordResponseStatusAndMessage","recordResponseItem","databaseId","debug","responseStatusName","httpStatus","message","getMessageFromResponsePayload","ids","includes","recordStatus","CONFLICT","test","length","UNPROCESSABLE_ENTITY","NOT_FOUND","String","addRecordResponseItem","correlationId","mongoOperator","pushMessages","messages","messageField"],"sources":["../src/utils.js"],"sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Shared modules for microservices of Melinda rest api batch import system\n*\n* Copyright (C) 2020-2021 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-rest-api-commons\n*\n* melinda-rest-api-commons program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-rest-api-commons is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport {createLogger} from '@natlibfi/melinda-backend-commons';\nimport {Error as ApiError} from '@natlibfi/melinda-commons';\nimport {IMPORT_JOB_STATE, OPERATIONS} from './constants';\nimport httpStatus from 'http-status';\n\nconst logger = createLogger();\n\nexport function logError(err) {\n if (err instanceof ApiError) {\n logger.error(JSON.stringify(err));\n return;\n }\n\n if (err === 'SIGINT') {\n logger.error(err);\n return;\n }\n\n logger.error(err.stack === undefined ? err : err.stack);\n}\n\nexport function createImportJobState(operation, state, queryImportJobState = false) {\n if (!(state in IMPORT_JOB_STATE)) {\n throw new Error('Invalid IMPORT_JOB_STATE');\n }\n\n if (!(operation in OPERATIONS)) {\n throw new Error('Invalid operation');\n }\n\n if (queryImportJobState) {\n const importJobStateWithOperation = `importJobState.${operation}`;\n const importJobStateForQuery = {[importJobStateWithOperation]: state};\n\n return importJobStateForQuery;\n }\n\n return {[operation]: state};\n}\n\nexport function createRecordResponseItem({responsePayload, responseStatus, recordMetadata, id}) {\n const recordResponseStatusAndMessage = getRecordResponseStatusAndMessage(responseStatus, responsePayload, id);\n const recordResponseItem = {\n databaseId: id || '000000000',\n recordMetadata: responsePayload.recordMetadata || recordMetadata || undefined,\n ...recordResponseStatusAndMessage\n };\n return recordResponseItem;\n}\n\n// eslint-disable-next-line max-statements\nfunction getRecordResponseStatusAndMessage(responseStatus, responsePayload, id) {\n\n logger.debug(`Response status: ${responseStatus} responsePayload: ${JSON.stringify(responsePayload)}`);\n const responseStatusName = httpStatus[`${responseStatus}_NAME`];\n logger.debug(`Response status name: ${responseStatusName}`);\n\n const message = getMessageFromResponsePayload(responsePayload);\n const ids = responsePayload.ids || [];\n\n logger.debug(`Response message: ${message}`);\n\n // Non-http statuses\n if (['UPDATED', 'CREATED', 'INVALID', 'ERROR', 'SKIPPED'].includes(responseStatus)) {\n return {recordStatus: responseStatus, message};\n }\n\n if (['UNKNOWN'].includes(responseStatus)) {\n return {recordStatus: responseStatus, message, ids};\n }\n\n // Duplicates and other CONFLICT statuses\n if ([httpStatus.CONFLICT, 'CONFLICT'].includes(responseStatus)) {\n if ((/^Duplicates in database/u).test(message)) {\n return {recordStatus: 'DUPLICATE', message, ids};\n }\n if ((/^MatchValidation for all/u).test(message)) {\n return {recordStatus: 'CONFLICT', message, ids};\n }\n\n // Use ids only if there are more than one id or the id in payload does not match databaseId\n if (ids.length > 1 || ids[0] !== id) {\n return {recordStatus: 'CONFLICT', message, ids};\n }\n return {recordStatus: 'CONFLICT', message};\n }\n\n if ([httpStatus.UNPROCESSABLE_ENTITY, 'UNPROCESSABLE_ENTITY'].includes(responseStatus)) {\n if (ids.length > 1 || ids[0] !== id) {\n return {recordStatus: 'UNPROCESSABLE_ENTITY', message, ids};\n }\n return {recordStatus: 'UNPROCESSABLE_ENTITY', message};\n }\n\n if ([httpStatus.NOT_FOUND, 'NOT_FOUND'].includes(responseStatus)) {\n return {recordStatus: 'NOT_FOUND', message};\n }\n\n // Otherwise\n return {recordStatus: 'ERROR', message};\n}\n\nfunction getMessageFromResponsePayload(responsePayload) {\n if (responsePayload.message) {\n return responsePayload.message;\n }\n if (typeof responsePayload === 'string' || responsePayload instanceof String) {\n return responsePayload;\n }\n return '';\n}\n\nexport async function addRecordResponseItem({recordResponseItem, correlationId, mongoOperator}) {\n await mongoOperator.pushMessages({correlationId, messages: [recordResponseItem], messageField: 'records'});\n return true;\n}\n\n"],"mappings":";;;;;;;;;;AA4BA;;AACA;;AACA;;AACA;;;;AA/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAOA,MAAMA,MAAM,GAAG,IAAAC,mCAAA,GAAf;;AAEO,SAASC,QAAT,CAAkBC,GAAlB,E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C,YAAd,CAA2B;IAACF,aAAD;IAAgBG,QAAQ,EAAE,CAACpB,kBAAD,CAA1B;IAAgDqB,YAAY,EAAE;EAA9D,CAA3B,CAAN;EACA,OAAO,IAAP;AACD"}
1
+ {"version":3,"file":"utils.js","names":["logger","createLogger","logError","err","ApiError","error","JSON","stringify","stack","undefined","createImportJobState","operation","state","queryImportJobState","IMPORT_JOB_STATE","Error","OPERATIONS","importJobStateWithOperation","importJobStateForQuery","createRecordResponseItem","responsePayload","responseStatus","recordMetadata","id","recordResponseStatusAndMessage","getRecordResponseStatusAndMessage","recordResponseItem","databaseId","debug","responseStatusName","httpStatus","message","getMessageFromResponsePayload","ids","includes","recordStatus","detailedRecordStatus","CONFLICT","test","length","UNPROCESSABLE_ENTITY","NOT_FOUND","String","addRecordResponseItem","correlationId","mongoOperator","pushMessages","messages","messageField"],"sources":["../src/utils.js"],"sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Shared modules for microservices of Melinda rest api batch import system\n*\n* Copyright (C) 2020-2021 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-rest-api-commons\n*\n* melinda-rest-api-commons program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-rest-api-commons is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport {createLogger} from '@natlibfi/melinda-backend-commons';\nimport {Error as ApiError} from '@natlibfi/melinda-commons';\nimport {IMPORT_JOB_STATE, OPERATIONS} from './constants';\nimport httpStatus from 'http-status';\n\nconst logger = createLogger();\n\nexport function logError(err) {\n if (err instanceof ApiError) {\n logger.error(JSON.stringify(err));\n return;\n }\n\n if (err === 'SIGINT') {\n logger.error(err);\n return;\n }\n\n logger.error(err.stack === undefined ? err : err.stack);\n}\n\nexport function createImportJobState(operation, state, queryImportJobState = false) {\n if (!(state in IMPORT_JOB_STATE)) {\n throw new Error('Invalid IMPORT_JOB_STATE');\n }\n\n if (!(operation in OPERATIONS)) {\n throw new Error('Invalid operation');\n }\n\n if (queryImportJobState) {\n const importJobStateWithOperation = `importJobState.${operation}`;\n const importJobStateForQuery = {[importJobStateWithOperation]: state};\n\n return importJobStateForQuery;\n }\n\n return {[operation]: state};\n}\n\nexport function createRecordResponseItem({responsePayload, responseStatus, recordMetadata, id}) {\n const recordResponseStatusAndMessage = getRecordResponseStatusAndMessage(responseStatus, responsePayload, id);\n const recordResponseItem = {\n databaseId: id || '000000000',\n recordMetadata: responsePayload.recordMetadata || recordMetadata || undefined,\n ...recordResponseStatusAndMessage\n };\n return recordResponseItem;\n}\n\n// eslint-disable-next-line max-statements\nfunction getRecordResponseStatusAndMessage(responseStatus, responsePayload, id) {\n\n logger.debug(`Response status: ${responseStatus} responsePayload: ${JSON.stringify(responsePayload)}`);\n const responseStatusName = httpStatus[`${responseStatus}_NAME`];\n logger.debug(`Response status name: ${responseStatusName}`);\n\n const message = getMessageFromResponsePayload(responsePayload);\n const ids = responsePayload.ids || [];\n\n logger.debug(`Response message: ${message}`);\n\n // We map responseStatus here for a wider recordStatus and more detailed detailedRecordStatus\n // recordStatus corresponds to RECORD_IMPORT_STATEs used in https://github.com/NatLibFi/melinda-record-import-commons-js\n\n // Non-http statuses\n if (['UPDATED', 'CREATED', 'INVALID', 'ERROR', 'SKIPPED'].includes(responseStatus)) {\n return {recordStatus: responseStatus, detailedRecordStatus: responseStatus, message};\n }\n\n if (['UNKNOWN'].includes(responseStatus)) {\n return {recordStatus: 'ERROR', detailedRecordStatus: responseStatus, message, ids};\n }\n\n // Duplicates and other CONFLICT statuses\n if ([httpStatus.CONFLICT, 'CONFLICT'].includes(responseStatus)) {\n if ((/^Duplicates in database/u).test(message)) {\n return {recordStatus: 'DUPLICATE', detailedRecordStatus: 'DUPLICATE', message, ids};\n }\n if ((/^MatchValidation for all/u).test(message)) {\n return {recordStatus: 'ERROR', detailedRecordStatus: 'CONFLICT', message, ids};\n }\n\n // Use ids only if there are more than one id or the id in payload does not match databaseId\n if (ids.length > 1 || ids[0] !== id) {\n return {recordStatus: 'ERROR', detailedRecordStatus: 'CONFLICT', message, ids};\n }\n return {recordStatus: 'ERROR', detailedRecordStatus: 'CONFLICT', message};\n }\n\n if ([httpStatus.UNPROCESSABLE_ENTITY, 'UNPROCESSABLE_ENTITY'].includes(responseStatus)) {\n if (ids.length > 1 || ids[0] !== id) {\n return {recordStatus: 'INVALID', detailedRecordStatus: 'UNPROCESSABLE_ENTITY', message, ids};\n }\n return {recordStatus: 'INVALID', detailedRecordStatus: 'UNPROCESSABLE_ENTITY', message};\n }\n\n if ([httpStatus.NOT_FOUND, 'NOT_FOUND'].includes(responseStatus)) {\n return {recordStatus: 'ERROR', detailedRecordStatus: 'NOT_FOUND', message};\n }\n\n // Otherwise\n return {recordStatus: 'ERROR', detailedRecordStatus: responseStatus, message};\n}\n\nfunction getMessageFromResponsePayload(responsePayload) {\n if (responsePayload.message) {\n return responsePayload.message;\n }\n if (typeof responsePayload === 'string' || responsePayload instanceof String) {\n return responsePayload;\n }\n return '';\n}\n\nexport async function addRecordResponseItem({recordResponseItem, correlationId, mongoOperator}) {\n await mongoOperator.pushMessages({correlationId, messages: [recordResponseItem], messageField: 'records'});\n return true;\n}\n\n"],"mappings":";;;;;;;;;;AA4BA;;AACA;;AACA;;AACA;;;;AA/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAOA,MAAMA,MAAM,GAAG,IAAAC,mCAAA,GAAf;;AAEO,SAASC,Q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AvC,EAAwD;EACtD,IAAIA,eAAe,CAACW,OAApB,EAA6B;IAC3B,OAAOX,eAAe,CAACW,OAAvB;EACD;;EACD,IAAI,OAAOX,eAAP,KAA2B,QAA3B,IAAuCA,eAAe,YAAYsB,MAAtE,EAA8E;IAC5E,OAAOtB,eAAP;EACD;;EACD,OAAO,EAAP;AACD;;AAEM,eAAeuB,qBAAf,CAAqC;EAACjB,kBAAD;EAAqBkB,aAArB;EAAoCC;AAApC,CAArC,EAAyF;EAC9F,MAAMA,aAAa,CAACC,YAAd,CAA2B;IAACF,aAAD;IAAgBG,QAAQ,EAAE,CAACrB,kBAAD,CAA1B;IAAgDsB,YAAY,EAAE;EAA9D,CAA3B,CAAN;EACA,OAAO,IAAP;AACD"}
package/package.json CHANGED
@@ -14,8 +14,8 @@
14
14
  "url": "git@github.com:natlibfi/melinda-rest-api-commons.git"
15
15
  },
16
16
  "license": "AGPL-3.0+",
17
- "version": "2.3.1-alpha.3",
18
- "main": "dist/index.js",
17
+ "version": "2.3.1-alpha.5",
18
+ "main": "./dist/index.js",
19
19
  "engines": {
20
20
  "node": ">=14"
21
21
  },