@sdflc/backend-helpers 1.0.79 → 1.0.80

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 (37) hide show
  1. package/build/BaseCore.js +496 -600
  2. package/build/BaseGateway.js +331 -377
  3. package/build/DataCache.js +16 -19
  4. package/build/Database.js +55 -74
  5. package/build/DbMigratorAndSeeder.js +88 -114
  6. package/build/RedisDataLoader.js +153 -184
  7. package/build/apiContext.js +35 -33
  8. package/build/baseController.js +9 -16
  9. package/build/commonValidators.js +22 -31
  10. package/build/configBulder.js +5 -1
  11. package/build/dbHelpers.js +19 -29
  12. package/build/dbSeeder.js +11 -20
  13. package/build/dbTableHelpers.js +10 -10
  14. package/build/downloadHelpers.js +15 -25
  15. package/build/esm/BaseCore.js +496 -600
  16. package/build/esm/BaseGateway.js +331 -377
  17. package/build/esm/DataCache.js +16 -19
  18. package/build/esm/Database.js +55 -74
  19. package/build/esm/DbMigratorAndSeeder.js +88 -114
  20. package/build/esm/RedisDataLoader.js +153 -184
  21. package/build/esm/apiContext.js +35 -33
  22. package/build/esm/baseController.js +9 -16
  23. package/build/esm/commonValidators.js +22 -31
  24. package/build/esm/configBulder.js +5 -1
  25. package/build/esm/dbHelpers.js +19 -29
  26. package/build/esm/dbSeeder.js +11 -20
  27. package/build/esm/dbTableHelpers.js +10 -10
  28. package/build/esm/downloadHelpers.js +15 -25
  29. package/build/esm/knexConfigBuilder.js +17 -7
  30. package/build/esm/passwordHelpers.js +7 -16
  31. package/build/esm/resolversHelpers.js +11 -4
  32. package/build/esm/userToken.js +2 -2
  33. package/build/knexConfigBuilder.js +17 -7
  34. package/build/passwordHelpers.js +7 -16
  35. package/build/resolversHelpers.js +11 -4
  36. package/build/userToken.js +2 -2
  37. package/package.json +2 -3
package/build/BaseCore.js CHANGED
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -39,27 +30,27 @@ const defaultValidators = {
39
30
  removeMany: commonValidators_1.validateRemoveMany,
40
31
  };
41
32
  class BaseCore {
33
+ measureTool = new utils_1.MeasureTool();
34
+ config;
35
+ logger;
42
36
  constructor(props) {
43
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;
44
- this.measureTool = new utils_1.MeasureTool();
45
37
  this.config = props || {};
46
38
  this.logger = this.config.logger instanceof utils_1.Logger ? this.config.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.ERROR });
47
39
  this.config.doAuthOnAction = {
48
- list: ((_a = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _a === void 0 ? void 0 : _a.list) != null ? (_b = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _b === void 0 ? void 0 : _b.list : props === null || props === void 0 ? void 0 : props.doAuth,
49
- get: ((_c = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _c === void 0 ? void 0 : _c.get) != null ? (_d = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _d === void 0 ? void 0 : _d.get : props === null || props === void 0 ? void 0 : props.doAuth,
50
- getMany: ((_e = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _e === void 0 ? void 0 : _e.getMany) != null ? (_f = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _f === void 0 ? void 0 : _f.getMany : props === null || props === void 0 ? void 0 : props.doAuth,
51
- create: ((_g = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _g === void 0 ? void 0 : _g.create) != null ? (_h = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _h === void 0 ? void 0 : _h.create : props === null || props === void 0 ? void 0 : props.doAuth,
52
- createMany: ((_j = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _j === void 0 ? void 0 : _j.createMany) != null ? (_k = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _k === void 0 ? void 0 : _k.createMany : props === null || props === void 0 ? void 0 : props.doAuth,
53
- update: ((_l = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _l === void 0 ? void 0 : _l.update) != null ? (_m = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _m === void 0 ? void 0 : _m.update : props === null || props === void 0 ? void 0 : props.doAuth,
54
- updateMany: ((_o = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _o === void 0 ? void 0 : _o.updateMany) != null ? (_p = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _p === void 0 ? void 0 : _p.updateMany : props === null || props === void 0 ? void 0 : props.doAuth,
55
- set: ((_q = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _q === void 0 ? void 0 : _q.set) != null ? (_r = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _r === void 0 ? void 0 : _r.set : props === null || props === void 0 ? void 0 : props.doAuth,
56
- remove: ((_s = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _s === void 0 ? void 0 : _s.remove) != null ? (_t = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _t === void 0 ? void 0 : _t.remove : props === null || props === void 0 ? void 0 : props.doAuth,
57
- removeMany: ((_u = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _u === void 0 ? void 0 : _u.removeMany) != null ? (_v = props === null || props === void 0 ? void 0 : props.doAuthOnAction) === null || _v === void 0 ? void 0 : _v.removeMany : props === null || props === void 0 ? void 0 : props.doAuth,
40
+ list: props?.doAuthOnAction?.list != null ? props?.doAuthOnAction?.list : props?.doAuth,
41
+ get: props?.doAuthOnAction?.get != null ? props?.doAuthOnAction?.get : props?.doAuth,
42
+ getMany: props?.doAuthOnAction?.getMany != null ? props?.doAuthOnAction?.getMany : props?.doAuth,
43
+ create: props?.doAuthOnAction?.create != null ? props?.doAuthOnAction?.create : props?.doAuth,
44
+ createMany: props?.doAuthOnAction?.createMany != null ? props?.doAuthOnAction?.createMany : props?.doAuth,
45
+ update: props?.doAuthOnAction?.update != null ? props?.doAuthOnAction?.update : props?.doAuth,
46
+ updateMany: props?.doAuthOnAction?.updateMany != null ? props?.doAuthOnAction?.updateMany : props?.doAuth,
47
+ set: props?.doAuthOnAction?.set != null ? props?.doAuthOnAction?.set : props?.doAuth,
48
+ remove: props?.doAuthOnAction?.remove != null ? props?.doAuthOnAction?.remove : props?.doAuth,
49
+ removeMany: props?.doAuthOnAction?.removeMany != null ? props?.doAuthOnAction?.removeMany : props?.doAuth,
58
50
  };
59
51
  }
60
52
  getIdType() {
61
- var _a;
62
- return (_a = this.config.idType) !== null && _a !== void 0 ? _a : constants_1.ID_TYPES.UNKNOWN;
53
+ return this.config.idType ?? constants_1.ID_TYPES.UNKNOWN;
63
54
  }
64
55
  getDb() {
65
56
  return this.config.db;
@@ -74,8 +65,7 @@ class BaseCore {
74
65
  return this.config.context.gateways || {};
75
66
  }
76
67
  getGateway(name) {
77
- var _a;
78
- return (_a = this.getGateways()) === null || _a === void 0 ? void 0 : _a[name || this.config.gatewayName];
68
+ return this.getGateways()?.[name || this.config.gatewayName];
79
69
  }
80
70
  getValidators() {
81
71
  return defaultValidators;
@@ -107,7 +97,7 @@ class BaseCore {
107
97
  if (ex instanceof api_helpers_1.OpResult) {
108
98
  return result.toJS();
109
99
  }
110
- Object.keys((ex === null || ex === void 0 ? void 0 : ex.errors) || {}).forEach((key) => {
100
+ Object.keys(ex?.errors || {}).forEach((key) => {
111
101
  const obj = ex.errors[key];
112
102
  if (Array.isArray(obj.errors)) {
113
103
  // if we have multiple rules failures the add them all
@@ -138,222 +128,206 @@ class BaseCore {
138
128
  result.addError('', msg, api_helpers_1.OP_RESULT_CODES.EXCEPTION);
139
129
  return result.toJS();
140
130
  }
141
- checkResult(args) {
142
- return __awaiter(this, void 0, void 0, function* () {
143
- const { hasTransaction, result, sameRequest, doingWhat } = args;
144
- if (sameRequest) {
145
- return;
131
+ async checkResult(args) {
132
+ const { hasTransaction, result, sameRequest, doingWhat } = args;
133
+ if (sameRequest) {
134
+ return;
135
+ }
136
+ if (hasTransaction && result) {
137
+ if (result.code >= api_helpers_1.OP_RESULT_CODES.OK) {
138
+ this.logger.debug(`Commit DB transaction on ${doingWhat}`);
139
+ await this.getDb().commitTransaction();
146
140
  }
147
- if (hasTransaction && result) {
148
- if (result.code >= api_helpers_1.OP_RESULT_CODES.OK) {
149
- this.logger.debug(`Commit DB transaction on ${doingWhat}`);
150
- yield this.getDb().commitTransaction();
151
- }
152
- else {
153
- this.logger.debug(`Rollback DB transaction on ${doingWhat} as action result code is '${result.code}'`);
154
- yield this.getDb().rollbackTransaction();
155
- }
141
+ else {
142
+ this.logger.debug(`Rollback DB transaction on ${doingWhat} as action result code is '${result.code}'`);
143
+ await this.getDb().rollbackTransaction();
156
144
  }
157
- });
145
+ }
158
146
  }
159
- runAction(opt) {
160
- return __awaiter(this, void 0, void 0, function* () {
161
- const { args, validate, doAuth, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace } = opt || {};
162
- // If we process action with the same requestId as requestId passed to the constructor it means
163
- // we are processing the same request from FE and can skip some of the operations like transactions and etc
164
- const sameRequest = !!this.config.context.requestId && (args === null || args === void 0 ? void 0 : args.requestId) === this.config.context.requestId;
165
- // TODO: Calculate total thread block time between async calls withing the request
166
- // this.measureTool.threadBlockTime(doingWhat, ({ name, durationMs }: any) => {
167
- // this.logger.debug(`The ${name} blocked thread for the time of ${durationMs} ms`);
168
- // });
169
- if (shouldLogArgs == null || shouldLogArgs === true) {
170
- this.logger.debug(`The ${doingWhat} started:`, args);
171
- }
172
- else {
173
- this.logger.debug(`The ${doingWhat} started`);
147
+ async runAction(opt) {
148
+ const { args, validate, doAuth, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace } = opt || {};
149
+ // If we process action with the same requestId as requestId passed to the constructor it means
150
+ // we are processing the same request from FE and can skip some of the operations like transactions and etc
151
+ const sameRequest = !!this.config.context.requestId && args?.requestId === this.config.context.requestId;
152
+ // TODO: Calculate total thread block time between async calls withing the request
153
+ // this.measureTool.threadBlockTime(doingWhat, ({ name, durationMs }: any) => {
154
+ // this.logger.debug(`The ${name} blocked thread for the time of ${durationMs} ms`);
155
+ // });
156
+ if (shouldLogArgs == null || shouldLogArgs === true) {
157
+ this.logger.debug(`The ${doingWhat} started:`, args);
158
+ }
159
+ else {
160
+ this.logger.debug(`The ${doingWhat} started`);
161
+ }
162
+ this.measureTool.start();
163
+ let step = doingWhat || '';
164
+ const setStep = (stepName) => {
165
+ step = stepName || step;
166
+ const time = this.measureTool.addCheckpoint(stepName);
167
+ if (stepName) {
168
+ this.logger.debug(`${time.name}. Since last step: ${time.durationMs} ms`);
174
169
  }
175
- this.measureTool.start();
176
- let step = doingWhat || '';
177
- const setStep = (stepName) => {
178
- step = stepName || step;
179
- const time = this.measureTool.addCheckpoint(stepName);
180
- if (stepName) {
181
- this.logger.debug(`${time.name}. Since last step: ${time.durationMs} ms`);
170
+ };
171
+ const actionOpt = {
172
+ core: this,
173
+ setStep,
174
+ sameRequest,
175
+ hasTransaction,
176
+ };
177
+ try {
178
+ if (!sameRequest) {
179
+ if (hasTransaction) {
180
+ this.logger.debug(`Start DB transaction on ${step}`);
181
+ await this.getDb().startTransaction();
182
182
  }
183
- };
184
- const actionOpt = {
185
- core: this,
186
- setStep,
187
- sameRequest,
188
- hasTransaction,
189
- };
190
- try {
191
- if (!sameRequest) {
192
- if (hasTransaction) {
193
- this.logger.debug(`Start DB transaction on ${step}`);
194
- yield this.getDb().startTransaction();
195
- }
196
- if (doAuth === true || (doAuth == null && this.config.doAuth)) {
197
- this.measureTool.addCheckpoint('Authenticate request: start');
198
- const [authResult, errMsg] = yield this.authenticate(opt, actionOpt);
199
- this.measureTool.addCheckpoint('Authenticate request: end');
200
- if (!authResult) {
201
- const result = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.UNAUTHORIZED }).addError('', errMsg);
202
- this.logger.error(`The ${step} requires authentication and it has failed:`, errMsg);
203
- yield this.checkResult({ hasTransaction, result, sameRequest, doingWhat });
204
- return result;
205
- }
206
- }
207
- else if (requireSpace == null || requireSpace === true) {
208
- this.measureTool.addCheckpoint('Find space: start');
209
- const [spaceResult, errMsg] = yield this.findSpace();
210
- this.measureTool.addCheckpoint('Find space: end');
211
- if (spaceResult !== true) {
212
- const result = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.UNAUTHORIZED }).addError('', errMsg);
213
- this.logger.error(`The ${step} requires a space and it has failed:`, errMsg);
214
- yield this.checkResult({ hasTransaction, result, sameRequest, doingWhat });
215
- return result;
216
- }
183
+ if (doAuth === true || (doAuth == null && this.config.doAuth)) {
184
+ this.measureTool.addCheckpoint('Authenticate request: start');
185
+ const [authResult, errMsg] = await this.authenticate(opt, actionOpt);
186
+ this.measureTool.addCheckpoint('Authenticate request: end');
187
+ if (!authResult) {
188
+ const result = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.UNAUTHORIZED }).addError('', errMsg);
189
+ this.logger.error(`The ${step} requires authentication and it has failed:`, errMsg);
190
+ await this.checkResult({ hasTransaction, result, sameRequest, doingWhat });
191
+ return result;
217
192
  }
218
193
  }
219
- let validatedItems = {};
220
- if (typeof validate === 'function') {
221
- this.measureTool.addCheckpoint('Validate parameters: start');
222
- // If we have validator provided, use it to validate data before running action
223
- // validator is expected to return an array:
224
- // [0] - true or validation error object,
225
- // [1] - an object with some fetched data to pass ot the action handler
226
- const valideResult = yield validate(args, actionOpt);
227
- let result = valideResult;
228
- if (Array.isArray(valideResult)) {
229
- result = valideResult[0];
230
- validatedItems = valideResult[1] || {};
231
- }
232
- // If validator returned null then consider the validation passed
233
- result = result != null ? result : true;
234
- this.measureTool.addCheckpoint('Validate parameters: end');
235
- if (result !== true) {
236
- // if there was an error then `result` is expected to be an object with the same structure as the checkit library does
237
- yield this.checkResult({ hasTransaction, result, sameRequest });
238
- return result.code != null ? result : new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED });
194
+ else if (requireSpace == null || requireSpace === true) {
195
+ this.measureTool.addCheckpoint('Find space: start');
196
+ const [spaceResult, errMsg] = await this.findSpace();
197
+ this.measureTool.addCheckpoint('Find space: end');
198
+ if (spaceResult !== true) {
199
+ const result = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.UNAUTHORIZED }).addError('', errMsg);
200
+ this.logger.error(`The ${step} requires a space and it has failed:`, errMsg);
201
+ await this.checkResult({ hasTransaction, result, sameRequest, doingWhat });
202
+ return result;
239
203
  }
240
204
  }
241
- let time = this.measureTool.stop();
242
- this.logger.debug(`Authorization and validation time for the ${doingWhat} took ${time.durationMs} ms`);
243
- const result = yield action(args, Object.assign(Object.assign({}, actionOpt), { validatedItems, args }));
244
- yield this.checkResult({ hasTransaction, result, sameRequest, doingWhat });
245
- time = this.measureTool.stop(doingWhat);
246
- this.logger.debug(`The ${time.name} process time is ${time.durationMs} ms`);
247
- return result;
248
205
  }
249
- catch (ex) {
250
- this.logger.error(`An exception has occurred on ${step}:`, ex);
251
- if (!sameRequest && hasTransaction) {
252
- this.logger.debug(`Rolling back DB transaction on ${step} due to an excaption`);
253
- yield this.getDb().rollbackTransaction();
254
- }
255
- let errMessage = '';
256
- try {
257
- errMessage = yield this.onException(args, Object.assign(Object.assign({}, actionOpt), { doingWhat, exception: ex }));
258
- if (check_types_1.default.function(onException)) {
259
- errMessage = yield onException(args, Object.assign(Object.assign({}, actionOpt), { doingWhat, exception: ex }));
260
- }
206
+ let validatedItems = {};
207
+ if (typeof validate === 'function') {
208
+ this.measureTool.addCheckpoint('Validate parameters: start');
209
+ // If we have validator provided, use it to validate data before running action
210
+ // validator is expected to return an array:
211
+ // [0] - true or validation error object,
212
+ // [1] - an object with some fetched data to pass ot the action handler
213
+ const valideResult = await validate(args, actionOpt);
214
+ let result = valideResult;
215
+ if (Array.isArray(valideResult)) {
216
+ result = valideResult[0];
217
+ validatedItems = valideResult[1] || {};
261
218
  }
262
- catch (ex2) {
263
- this.logger.error(`An exception has occured when handling exception:`, ex2);
219
+ // If validator returned null then consider the validation passed
220
+ result = result != null ? result : true;
221
+ this.measureTool.addCheckpoint('Validate parameters: end');
222
+ if (result !== true) {
223
+ // if there was an error then `result` is expected to be an object with the same structure as the checkit library does
224
+ await this.checkResult({ hasTransaction, result, sameRequest });
225
+ return result.code != null ? result : new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED });
264
226
  }
265
- if (!errMessage) {
266
- errMessage = doingWhat;
267
- }
268
- if (doingWhat !== step) {
269
- errMessage = `${step} failed on ${doingWhat}`;
227
+ }
228
+ let time = this.measureTool.stop();
229
+ this.logger.debug(`Authorization and validation time for the ${doingWhat} took ${time.durationMs} ms`);
230
+ const result = await action(args, { ...actionOpt, validatedItems, args });
231
+ await this.checkResult({ hasTransaction, result, sameRequest, doingWhat });
232
+ time = this.measureTool.stop(doingWhat);
233
+ this.logger.debug(`The ${time.name} process time is ${time.durationMs} ms`);
234
+ return result;
235
+ }
236
+ catch (ex) {
237
+ this.logger.error(`An exception has occurred on ${step}:`, ex);
238
+ if (!sameRequest && hasTransaction) {
239
+ this.logger.debug(`Rolling back DB transaction on ${step} due to an excaption`);
240
+ await this.getDb().rollbackTransaction();
241
+ }
242
+ let errMessage = '';
243
+ try {
244
+ errMessage = await this.onException(args, { ...actionOpt, doingWhat, exception: ex });
245
+ if (check_types_1.default.function(onException)) {
246
+ errMessage = await onException(args, { ...actionOpt, doingWhat, exception: ex });
270
247
  }
271
- const time = this.measureTool.stop(doingWhat);
272
- this.logger.debug(`The ${time.name} process time is ${time.durationMs} ms`);
273
- return this.exceptionFailure(ex, errMessage);
274
248
  }
275
- });
276
- }
277
- list(args) {
278
- return __awaiter(this, void 0, void 0, function* () {
279
- var _a, _b, _c, _d;
280
- return this.runAction({
281
- args,
282
- doAuth: (_a = this.config.doAuthOnAction) === null || _a === void 0 ? void 0 : _a.list,
283
- actionName: constants_1.ACTIONS.LIST,
284
- validate: this.getValidators().list,
285
- accessRights: [utils_1.ACCESS_RIGHTS.LIST],
286
- action: (args, opt) => __awaiter(this, void 0, void 0, function* () {
287
- var _a;
288
- const object = yield this.beforeList(args, opt);
289
- if (object instanceof api_helpers_1.OpResult) {
290
- return object;
291
- }
292
- const items = yield ((_a = this.getContext().gateways[this.config.gatewayName]) === null || _a === void 0 ? void 0 : _a.list(object));
293
- const result = yield this.afterList(items, opt);
294
- // ON NO DATA RETURN EMPTY CODE
295
- return this.success(result);
296
- }),
297
- hasTransaction: false,
298
- doingWhat: (_d = (_c = (_b = this.config.doingWhat) === null || _b === void 0 ? void 0 : _b.list) !== null && _c !== void 0 ? _c : this.config.name) !== null && _d !== void 0 ? _d : 'listing',
299
- });
300
- });
301
- }
302
- get(args) {
303
- return __awaiter(this, void 0, void 0, function* () {
304
- var _a, _b, _c, _d;
305
- return this.runAction({
306
- args,
307
- doAuth: (_a = this.config.doAuthOnAction) === null || _a === void 0 ? void 0 : _a.get,
308
- actionName: constants_1.ACTIONS.GET,
309
- validate: this.getValidators().get,
310
- accessRights: [utils_1.ACCESS_RIGHTS.GET],
311
- action: (args, opt) => __awaiter(this, void 0, void 0, function* () {
312
- var _a;
313
- const args2use = yield this.beforeGet(args, opt);
314
- if (args2use instanceof api_helpers_1.OpResult) {
315
- return args2use;
316
- }
317
- if ((args2use === null || args2use === void 0 ? void 0 : args2use.id) == null) {
318
- return this.failure(api_helpers_1.OP_RESULT_CODES.NOT_FOUND, '', []);
319
- }
320
- const item = yield ((_a = this.getContext().gateways[this.config.gatewayName]) === null || _a === void 0 ? void 0 : _a.get(args2use === null || args2use === void 0 ? void 0 : args2use.id));
321
- const result = yield this.afterGet(item, opt);
322
- if (!result) {
323
- return this.failure(api_helpers_1.OP_RESULT_CODES.NOT_FOUND, '', []);
324
- }
325
- return this.success([result]);
326
- }),
327
- hasTransaction: false,
328
- doingWhat: (_d = (_c = (_b = this.config.doingWhat) === null || _b === void 0 ? void 0 : _b.get) !== null && _c !== void 0 ? _c : this.config.name) !== null && _d !== void 0 ? _d : 'getting an item',
329
- });
330
- });
249
+ catch (ex2) {
250
+ this.logger.error(`An exception has occured when handling exception:`, ex2);
251
+ }
252
+ if (!errMessage) {
253
+ errMessage = doingWhat;
254
+ }
255
+ if (doingWhat !== step) {
256
+ errMessage = `${step} failed on ${doingWhat}`;
257
+ }
258
+ const time = this.measureTool.stop(doingWhat);
259
+ this.logger.debug(`The ${time.name} process time is ${time.durationMs} ms`);
260
+ return this.exceptionFailure(ex, errMessage);
261
+ }
331
262
  }
332
- getMany(args) {
333
- return __awaiter(this, void 0, void 0, function* () {
334
- var _a, _b, _c, _d;
335
- return this.runAction({
336
- args,
337
- doAuth: (_a = this.config.doAuthOnAction) === null || _a === void 0 ? void 0 : _a.getMany,
338
- actionName: constants_1.ACTIONS.GET_MANY,
339
- validate: this.getValidators().getMany,
340
- accessRights: [utils_1.ACCESS_RIGHTS.GET],
341
- action: (args, opt) => __awaiter(this, void 0, void 0, function* () {
342
- var _a;
343
- const args2use = yield this.beforeGetMany(args, opt);
344
- if (args2use instanceof api_helpers_1.OpResult) {
345
- return args2use;
346
- }
347
- if (!Array.isArray(args2use === null || args2use === void 0 ? void 0 : args2use.ids)) {
348
- return this.failure(api_helpers_1.OP_RESULT_CODES.NOT_FOUND, '', []);
349
- }
350
- const items = yield ((_a = this.getContext().gateways[this.config.gatewayName]) === null || _a === void 0 ? void 0 : _a.getMany(args2use.ids));
351
- const result = yield this.afterGetMany(items, opt);
352
- return this.success(result);
353
- }),
354
- hasTransaction: false,
355
- doingWhat: (_d = (_c = (_b = this.config.doingWhat) === null || _b === void 0 ? void 0 : _b.getMany) !== null && _c !== void 0 ? _c : this.config.name) !== null && _d !== void 0 ? _d : 'geting multiple items',
356
- });
263
+ async list(args) {
264
+ return this.runAction({
265
+ args,
266
+ doAuth: this.config.doAuthOnAction?.list,
267
+ actionName: constants_1.ACTIONS.LIST,
268
+ validate: this.getValidators().list,
269
+ accessRights: [utils_1.ACCESS_RIGHTS.LIST],
270
+ action: async (args, opt) => {
271
+ const object = await this.beforeList(args, opt);
272
+ if (object instanceof api_helpers_1.OpResult) {
273
+ return object;
274
+ }
275
+ const items = await this.getContext().gateways[this.config.gatewayName]?.list(object);
276
+ const result = await this.afterList(items, opt);
277
+ // ON NO DATA RETURN EMPTY CODE
278
+ return this.success(result);
279
+ },
280
+ hasTransaction: false,
281
+ doingWhat: this.config.doingWhat?.list ?? this.config.name ?? 'listing',
282
+ });
283
+ }
284
+ async get(args) {
285
+ return this.runAction({
286
+ args,
287
+ doAuth: this.config.doAuthOnAction?.get,
288
+ actionName: constants_1.ACTIONS.GET,
289
+ validate: this.getValidators().get,
290
+ accessRights: [utils_1.ACCESS_RIGHTS.GET],
291
+ action: async (args, opt) => {
292
+ const args2use = await this.beforeGet(args, opt);
293
+ if (args2use instanceof api_helpers_1.OpResult) {
294
+ return args2use;
295
+ }
296
+ if (args2use?.id == null) {
297
+ return this.failure(api_helpers_1.OP_RESULT_CODES.NOT_FOUND, '', []);
298
+ }
299
+ const item = await this.getContext().gateways[this.config.gatewayName]?.get(args2use?.id);
300
+ const result = await this.afterGet(item, opt);
301
+ if (!result) {
302
+ return this.failure(api_helpers_1.OP_RESULT_CODES.NOT_FOUND, '', []);
303
+ }
304
+ return this.success([result]);
305
+ },
306
+ hasTransaction: false,
307
+ doingWhat: this.config.doingWhat?.get ?? this.config.name ?? 'getting an item',
308
+ });
309
+ }
310
+ async getMany(args) {
311
+ return this.runAction({
312
+ args,
313
+ doAuth: this.config.doAuthOnAction?.getMany,
314
+ actionName: constants_1.ACTIONS.GET_MANY,
315
+ validate: this.getValidators().getMany,
316
+ accessRights: [utils_1.ACCESS_RIGHTS.GET],
317
+ action: async (args, opt) => {
318
+ const args2use = await this.beforeGetMany(args, opt);
319
+ if (args2use instanceof api_helpers_1.OpResult) {
320
+ return args2use;
321
+ }
322
+ if (!Array.isArray(args2use?.ids)) {
323
+ return this.failure(api_helpers_1.OP_RESULT_CODES.NOT_FOUND, '', []);
324
+ }
325
+ const items = await this.getContext().gateways[this.config.gatewayName]?.getMany(args2use.ids);
326
+ const result = await this.afterGetMany(items, opt);
327
+ return this.success(result);
328
+ },
329
+ hasTransaction: false,
330
+ doingWhat: this.config.doingWhat?.getMany ?? this.config.name ?? 'geting multiple items',
357
331
  });
358
332
  }
359
333
  getGatewayToSetOrerNo() {
@@ -362,192 +336,162 @@ class BaseCore {
362
336
  getFilterToSetOrderNo(args) {
363
337
  return {};
364
338
  }
365
- create(args) {
366
- return __awaiter(this, void 0, void 0, function* () {
367
- var _a, _b, _c, _d;
368
- return this.runAction({
369
- args,
370
- doAuth: (_a = this.config.doAuthOnAction) === null || _a === void 0 ? void 0 : _a.create,
371
- actionName: constants_1.ACTIONS.CREATE,
372
- validate: this.getValidators().create,
373
- accessRights: [utils_1.ACCESS_RIGHTS.CREATE],
374
- action: (args, opt) => __awaiter(this, void 0, void 0, function* () {
375
- var _a;
376
- const { params } = args || {};
377
- if (this.config.hasOrderNo === true) {
378
- this.setOrderNo({
379
- params,
380
- filter: this.getFilterToSetOrderNo({ params, opt }),
381
- gateway: this.getGatewayToSetOrerNo(),
382
- });
383
- }
384
- const object = yield this.beforeCreate(params, opt);
385
- if (object instanceof api_helpers_1.OpResult) {
386
- return object;
387
- }
388
- const items = yield ((_a = this.getContext().gateways[this.config.gatewayName]) === null || _a === void 0 ? void 0 : _a.create(object));
389
- const result = yield this.afterCreate(items, opt);
390
- return this.success(result);
391
- }),
392
- hasTransaction: true,
393
- doingWhat: (_d = (_c = (_b = this.config.doingWhat) === null || _b === void 0 ? void 0 : _b.create) !== null && _c !== void 0 ? _c : this.config.name) !== null && _d !== void 0 ? _d : 'creating an item',
394
- });
395
- });
396
- }
397
- createMany(args) {
398
- return __awaiter(this, void 0, void 0, function* () {
399
- var _a, _b, _c, _d;
400
- return this.runAction({
401
- args,
402
- doAuth: (_a = this.config.doAuthOnAction) === null || _a === void 0 ? void 0 : _a.createMany,
403
- actionName: constants_1.ACTIONS.CREATE_MANY,
404
- validate: this.getValidators().createMany,
405
- accessRights: [utils_1.ACCESS_RIGHTS.CREATE],
406
- action: (args, opt) => __awaiter(this, void 0, void 0, function* () {
407
- var _a;
408
- const { params } = args || {};
409
- const objects = yield this.beforeCreateMany(params, opt);
410
- if (objects instanceof api_helpers_1.OpResult) {
411
- return objects;
412
- }
413
- const items = yield ((_a = this.getContext().gateways[this.config.gatewayName]) === null || _a === void 0 ? void 0 : _a.create(objects));
414
- const result = yield this.afterCreateMany(items, opt);
415
- return this.success(result);
416
- }),
417
- hasTransaction: true,
418
- doingWhat: (_d = (_c = (_b = this.config.doingWhat) === null || _b === void 0 ? void 0 : _b.createMany) !== null && _c !== void 0 ? _c : this.config.name) !== null && _d !== void 0 ? _d : 'creating multiple items',
419
- });
420
- });
421
- }
422
- update(args) {
423
- return __awaiter(this, void 0, void 0, function* () {
424
- var _a, _b, _c, _d;
425
- return this.runAction({
426
- args,
427
- doAuth: (_a = this.config.doAuthOnAction) === null || _a === void 0 ? void 0 : _a.update,
428
- actionName: constants_1.ACTIONS.UPDATE,
429
- validate: this.getValidators().update,
430
- accessRights: [utils_1.ACCESS_RIGHTS.UPDATE],
431
- action: (args, opt) => __awaiter(this, void 0, void 0, function* () {
432
- var _a;
433
- const { where, params } = args || {};
434
- const object = yield this.beforeUpdate(params, opt);
435
- if (object instanceof api_helpers_1.OpResult) {
436
- return object;
437
- }
438
- const items = yield ((_a = this.getContext().gateways[this.config.gatewayName]) === null || _a === void 0 ? void 0 : _a.update(where, object));
439
- const result = yield this.afterUpdate(items, opt);
440
- return this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND);
441
- }),
442
- hasTransaction: true,
443
- doingWhat: (_d = (_c = (_b = this.config.doingWhat) === null || _b === void 0 ? void 0 : _b.update) !== null && _c !== void 0 ? _c : this.config.name) !== null && _d !== void 0 ? _d : 'updating an item',
444
- });
445
- });
446
- }
447
- updateMany(args) {
448
- return __awaiter(this, void 0, void 0, function* () {
449
- var _a, _b, _c, _d;
450
- return this.runAction({
451
- args,
452
- doAuth: (_a = this.config.doAuthOnAction) === null || _a === void 0 ? void 0 : _a.updateMany,
453
- actionName: constants_1.ACTIONS.UPDATE_MANY,
454
- validate: this.getValidators().updateMany,
455
- accessRights: [utils_1.ACCESS_RIGHTS.UPDATE],
456
- action: (args, opt) => __awaiter(this, void 0, void 0, function* () {
457
- var _a;
458
- const { params } = args || {};
459
- const object = yield this.beforeUpdateMany(params, opt);
460
- if (object instanceof api_helpers_1.OpResult) {
461
- return object;
462
- }
463
- const items = yield ((_a = this.getContext().gateways[this.config.gatewayName]) === null || _a === void 0 ? void 0 : _a.updateMany(object));
464
- const result = yield this.afterUpdateMany(items, opt);
465
- return this.success(result);
466
- }),
467
- hasTransaction: true,
468
- doingWhat: (_d = (_c = (_b = this.config.doingWhat) === null || _b === void 0 ? void 0 : _b.updateMany) !== null && _c !== void 0 ? _c : this.config.name) !== null && _d !== void 0 ? _d : 'updating multiple items',
469
- });
470
- });
471
- }
472
- set(args) {
473
- return __awaiter(this, void 0, void 0, function* () {
474
- var _a, _b, _c, _d;
475
- return this.runAction({
476
- args,
477
- doAuth: (_a = this.config.doAuthOnAction) === null || _a === void 0 ? void 0 : _a.set,
478
- actionName: constants_1.ACTIONS.SET,
479
- validate: this.getValidators().set,
480
- accessRights: [utils_1.ACCESS_RIGHTS.CREATE, utils_1.ACCESS_RIGHTS.UPDATE],
481
- action: (args, opt /* { setStep, validatedItems, sameRequest } */) => __awaiter(this, void 0, void 0, function* () {
482
- var _a;
483
- const { params } = args || {};
484
- const object = yield this.beforeSet(params, opt);
485
- if (object instanceof api_helpers_1.OpResult) {
486
- return object;
487
- }
488
- const items = yield ((_a = this.getContext().gateways[this.config.gatewayName]) === null || _a === void 0 ? void 0 : _a.set(object));
489
- const result = yield this.afterSet(items, opt);
490
- return this.success(result);
491
- }),
492
- hasTransaction: true,
493
- doingWhat: (_d = (_c = (_b = this.config.doingWhat) === null || _b === void 0 ? void 0 : _b.updateMany) !== null && _c !== void 0 ? _c : this.config.name) !== null && _d !== void 0 ? _d : 'updating multiple items',
494
- });
495
- });
496
- }
497
- remove(args) {
498
- return __awaiter(this, void 0, void 0, function* () {
499
- var _a, _b, _c, _d;
500
- return this.runAction({
501
- args,
502
- doAuth: (_a = this.config.doAuthOnAction) === null || _a === void 0 ? void 0 : _a.remove,
503
- actionName: constants_1.ACTIONS.REMOVE,
504
- validate: this.getValidators().remove,
505
- accessRights: [utils_1.ACCESS_RIGHTS.REMOVE],
506
- action: (args, opt) => __awaiter(this, void 0, void 0, function* () {
507
- var _a;
508
- const { where } = args || {};
509
- const object = yield this.beforeRemove(where, opt);
510
- if (object instanceof api_helpers_1.OpResult) {
511
- return object;
512
- }
513
- const items = yield ((_a = this.getContext().gateways[this.config.gatewayName]) === null || _a === void 0 ? void 0 : _a.remove(object));
514
- const result = yield this.afterRemove(items, opt);
515
- return this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND);
516
- }),
517
- hasTransaction: false,
518
- doingWhat: (_d = (_c = (_b = this.config.doingWhat) === null || _b === void 0 ? void 0 : _b.remove) !== null && _c !== void 0 ? _c : this.config.name) !== null && _d !== void 0 ? _d : 'removing an item',
519
- });
520
- });
521
- }
522
- removeMany(args) {
523
- return __awaiter(this, void 0, void 0, function* () {
524
- var _a, _b, _c, _d;
525
- return this.runAction({
526
- args,
527
- doAuth: (_a = this.config.doAuthOnAction) === null || _a === void 0 ? void 0 : _a.removeMany,
528
- actionName: constants_1.ACTIONS.REMOVE_MANY,
529
- validate: this.getValidators().removeMany,
530
- accessRights: [utils_1.ACCESS_RIGHTS.REMOVE],
531
- action: (args, opt) => __awaiter(this, void 0, void 0, function* () {
532
- var _a;
533
- const { where } = args || {};
534
- const object = yield this.beforeRemoveMany(where, opt);
535
- if (object instanceof api_helpers_1.OpResult) {
536
- return object;
537
- }
538
- const items = yield ((_a = this.getContext().gateways[this.config.gatewayName]) === null || _a === void 0 ? void 0 : _a.remove(object));
539
- const result = yield this.afterRemoveMany(items, opt);
540
- return this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND);
541
- }),
542
- hasTransaction: false,
543
- doingWhat: (_d = (_c = (_b = this.config.doingWhat) === null || _b === void 0 ? void 0 : _b.removeMany) !== null && _c !== void 0 ? _c : this.config.name) !== null && _d !== void 0 ? _d : 'removing multiple items',
544
- });
339
+ async create(args) {
340
+ return this.runAction({
341
+ args,
342
+ doAuth: this.config.doAuthOnAction?.create,
343
+ actionName: constants_1.ACTIONS.CREATE,
344
+ validate: this.getValidators().create,
345
+ accessRights: [utils_1.ACCESS_RIGHTS.CREATE],
346
+ action: async (args, opt) => {
347
+ const { params } = args || {};
348
+ if (this.config.hasOrderNo === true) {
349
+ this.setOrderNo({
350
+ params,
351
+ filter: this.getFilterToSetOrderNo({ params, opt }),
352
+ gateway: this.getGatewayToSetOrerNo(),
353
+ });
354
+ }
355
+ const object = await this.beforeCreate(params, opt);
356
+ if (object instanceof api_helpers_1.OpResult) {
357
+ return object;
358
+ }
359
+ const items = await this.getContext().gateways[this.config.gatewayName]?.create(object);
360
+ const result = await this.afterCreate(items, opt);
361
+ return this.success(result);
362
+ },
363
+ hasTransaction: true,
364
+ doingWhat: this.config.doingWhat?.create ?? this.config.name ?? 'creating an item',
365
+ });
366
+ }
367
+ async createMany(args) {
368
+ return this.runAction({
369
+ args,
370
+ doAuth: this.config.doAuthOnAction?.createMany,
371
+ actionName: constants_1.ACTIONS.CREATE_MANY,
372
+ validate: this.getValidators().createMany,
373
+ accessRights: [utils_1.ACCESS_RIGHTS.CREATE],
374
+ action: async (args, opt) => {
375
+ const { params } = args || {};
376
+ const objects = await this.beforeCreateMany(params, opt);
377
+ if (objects instanceof api_helpers_1.OpResult) {
378
+ return objects;
379
+ }
380
+ const items = await this.getContext().gateways[this.config.gatewayName]?.create(objects);
381
+ const result = await this.afterCreateMany(items, opt);
382
+ return this.success(result);
383
+ },
384
+ hasTransaction: true,
385
+ doingWhat: this.config.doingWhat?.createMany ?? this.config.name ?? 'creating multiple items',
386
+ });
387
+ }
388
+ async update(args) {
389
+ return this.runAction({
390
+ args,
391
+ doAuth: this.config.doAuthOnAction?.update,
392
+ actionName: constants_1.ACTIONS.UPDATE,
393
+ validate: this.getValidators().update,
394
+ accessRights: [utils_1.ACCESS_RIGHTS.UPDATE],
395
+ action: async (args, opt) => {
396
+ const { where, params } = args || {};
397
+ const object = await this.beforeUpdate(params, opt);
398
+ if (object instanceof api_helpers_1.OpResult) {
399
+ return object;
400
+ }
401
+ const items = await this.getContext().gateways[this.config.gatewayName]?.update(where, object);
402
+ const result = await this.afterUpdate(items, opt);
403
+ return this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND);
404
+ },
405
+ hasTransaction: true,
406
+ doingWhat: this.config.doingWhat?.update ?? this.config.name ?? 'updating an item',
407
+ });
408
+ }
409
+ async updateMany(args) {
410
+ return this.runAction({
411
+ args,
412
+ doAuth: this.config.doAuthOnAction?.updateMany,
413
+ actionName: constants_1.ACTIONS.UPDATE_MANY,
414
+ validate: this.getValidators().updateMany,
415
+ accessRights: [utils_1.ACCESS_RIGHTS.UPDATE],
416
+ action: async (args, opt) => {
417
+ const { params } = args || {};
418
+ const object = await this.beforeUpdateMany(params, opt);
419
+ if (object instanceof api_helpers_1.OpResult) {
420
+ return object;
421
+ }
422
+ const items = await this.getContext().gateways[this.config.gatewayName]?.updateMany(object);
423
+ const result = await this.afterUpdateMany(items, opt);
424
+ return this.success(result);
425
+ },
426
+ hasTransaction: true,
427
+ doingWhat: this.config.doingWhat?.updateMany ?? this.config.name ?? 'updating multiple items',
428
+ });
429
+ }
430
+ async set(args) {
431
+ return this.runAction({
432
+ args,
433
+ doAuth: this.config.doAuthOnAction?.set,
434
+ actionName: constants_1.ACTIONS.SET,
435
+ validate: this.getValidators().set,
436
+ accessRights: [utils_1.ACCESS_RIGHTS.CREATE, utils_1.ACCESS_RIGHTS.UPDATE],
437
+ action: async (args, opt /* { setStep, validatedItems, sameRequest } */) => {
438
+ const { params } = args || {};
439
+ const object = await this.beforeSet(params, opt);
440
+ if (object instanceof api_helpers_1.OpResult) {
441
+ return object;
442
+ }
443
+ const items = await this.getContext().gateways[this.config.gatewayName]?.set(object);
444
+ const result = await this.afterSet(items, opt);
445
+ return this.success(result);
446
+ },
447
+ hasTransaction: true,
448
+ doingWhat: this.config.doingWhat?.updateMany ?? this.config.name ?? 'updating multiple items',
449
+ });
450
+ }
451
+ async remove(args) {
452
+ return this.runAction({
453
+ args,
454
+ doAuth: this.config.doAuthOnAction?.remove,
455
+ actionName: constants_1.ACTIONS.REMOVE,
456
+ validate: this.getValidators().remove,
457
+ accessRights: [utils_1.ACCESS_RIGHTS.REMOVE],
458
+ action: async (args, opt) => {
459
+ const { where } = args || {};
460
+ const object = await this.beforeRemove(where, opt);
461
+ if (object instanceof api_helpers_1.OpResult) {
462
+ return object;
463
+ }
464
+ const items = await this.getContext().gateways[this.config.gatewayName]?.remove(object);
465
+ const result = await this.afterRemove(items, opt);
466
+ return this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND);
467
+ },
468
+ hasTransaction: false,
469
+ doingWhat: this.config.doingWhat?.remove ?? this.config.name ?? 'removing an item',
470
+ });
471
+ }
472
+ async removeMany(args) {
473
+ return this.runAction({
474
+ args,
475
+ doAuth: this.config.doAuthOnAction?.removeMany,
476
+ actionName: constants_1.ACTIONS.REMOVE_MANY,
477
+ validate: this.getValidators().removeMany,
478
+ accessRights: [utils_1.ACCESS_RIGHTS.REMOVE],
479
+ action: async (args, opt) => {
480
+ const { where } = args || {};
481
+ const object = await this.beforeRemoveMany(where, opt);
482
+ if (object instanceof api_helpers_1.OpResult) {
483
+ return object;
484
+ }
485
+ const items = await this.getContext().gateways[this.config.gatewayName]?.remove(object);
486
+ const result = await this.afterRemoveMany(items, opt);
487
+ return this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND);
488
+ },
489
+ hasTransaction: false,
490
+ doingWhat: this.config.doingWhat?.removeMany ?? this.config.name ?? 'removing multiple items',
545
491
  });
546
492
  }
547
- defaultAfterAndBefore(params, opt) {
548
- return __awaiter(this, void 0, void 0, function* () {
549
- return params;
550
- });
493
+ async defaultAfterAndBefore(params, opt) {
494
+ return params;
551
495
  }
552
496
  /**
553
497
  * Used to transform an object before sending it in the response
@@ -567,205 +511,160 @@ class BaseCore {
567
511
  processItemOnIn(item, opt) {
568
512
  return this.defaultAfterAndBefore(item, opt);
569
513
  }
570
- beforeGet(item, opt) {
571
- return __awaiter(this, void 0, void 0, function* () {
572
- return this.defaultAfterAndBefore(item, opt);
573
- });
514
+ async beforeGet(item, opt) {
515
+ return this.defaultAfterAndBefore(item, opt);
574
516
  }
575
- beforeGetMany(items, opt) {
576
- return __awaiter(this, void 0, void 0, function* () {
577
- return this.defaultAfterAndBefore(items, opt);
578
- });
517
+ async beforeGetMany(items, opt) {
518
+ return this.defaultAfterAndBefore(items, opt);
579
519
  }
580
- beforeList(filter, opt) {
581
- return __awaiter(this, void 0, void 0, function* () {
582
- return this.defaultAfterAndBefore(filter, opt);
583
- });
520
+ async beforeList(filter, opt) {
521
+ return this.defaultAfterAndBefore(filter, opt);
584
522
  }
585
- afterGet(item, opt) {
586
- return __awaiter(this, void 0, void 0, function* () {
587
- return this.processItemOnOut(item, opt);
588
- });
523
+ async afterGet(item, opt) {
524
+ return this.processItemOnOut(item, opt);
589
525
  }
590
- afterGetMany(items, opt) {
591
- return __awaiter(this, void 0, void 0, function* () {
592
- return items.map((item) => this.processItemOnOut(item, opt));
593
- });
526
+ async afterGetMany(items, opt) {
527
+ return items.map((item) => this.processItemOnOut(item, opt));
594
528
  }
595
- afterList(items, opt) {
596
- return __awaiter(this, void 0, void 0, function* () {
597
- return items.map((item) => this.processItemOnOut(item, opt));
598
- });
529
+ async afterList(items, opt) {
530
+ return items.map((item) => this.processItemOnOut(item, opt));
599
531
  }
600
- beforeCreate(params, opt) {
601
- return __awaiter(this, void 0, void 0, function* () {
602
- return this.processItemOnIn(params, opt);
603
- });
532
+ async beforeCreate(params, opt) {
533
+ return this.processItemOnIn(params, opt);
604
534
  }
605
- afterCreate(items, opt) {
606
- return __awaiter(this, void 0, void 0, function* () {
607
- return items.map((item) => this.processItemOnOut(item, opt));
608
- });
535
+ async afterCreate(items, opt) {
536
+ return items.map((item) => this.processItemOnOut(item, opt));
609
537
  }
610
- beforeCreateMany(items, opt) {
611
- return __awaiter(this, void 0, void 0, function* () {
612
- return items.map((item) => this.processItemOnIn(item, opt));
613
- });
538
+ async beforeCreateMany(items, opt) {
539
+ return items.map((item) => this.processItemOnIn(item, opt));
614
540
  }
615
- afterCreateMany(items, opt) {
616
- return __awaiter(this, void 0, void 0, function* () {
617
- return items.map((item) => this.processItemOnOut(item, opt));
618
- });
541
+ async afterCreateMany(items, opt) {
542
+ return items.map((item) => this.processItemOnOut(item, opt));
619
543
  }
620
- beforeUpdate(params, opt) {
621
- return __awaiter(this, void 0, void 0, function* () {
622
- return this.processItemOnIn(params, opt);
623
- });
544
+ async beforeUpdate(params, opt) {
545
+ return this.processItemOnIn(params, opt);
624
546
  }
625
- afterUpdate(items, opt) {
626
- return __awaiter(this, void 0, void 0, function* () {
627
- return items.map((item) => this.processItemOnOut(item, opt));
628
- });
547
+ async afterUpdate(items, opt) {
548
+ return items.map((item) => this.processItemOnOut(item, opt));
629
549
  }
630
- beforeUpdateMany(items, opt) {
631
- return __awaiter(this, void 0, void 0, function* () {
632
- return items.map((item) => {
633
- return {
634
- params: this.processItemOnIn(item.params, opt),
635
- where: item.where,
636
- };
637
- });
550
+ async beforeUpdateMany(items, opt) {
551
+ return items.map((item) => {
552
+ return {
553
+ params: this.processItemOnIn(item.params, opt),
554
+ where: item.where,
555
+ };
638
556
  });
639
557
  }
640
- afterUpdateMany(items, opt) {
641
- return __awaiter(this, void 0, void 0, function* () {
642
- return items.map((item) => this.processItemOnOut(item, opt));
643
- });
558
+ async afterUpdateMany(items, opt) {
559
+ return items.map((item) => this.processItemOnOut(item, opt));
644
560
  }
645
- beforeSet(params, opt) {
646
- return __awaiter(this, void 0, void 0, function* () {
647
- return (0, lodash_1.castArray)(params).map((item) => this.processItemOnIn(item, opt));
648
- });
561
+ async beforeSet(params, opt) {
562
+ return (0, lodash_1.castArray)(params).map((item) => this.processItemOnIn(item, opt));
649
563
  }
650
- afterSet(items, opt) {
651
- return __awaiter(this, void 0, void 0, function* () {
652
- return items.map((item) => this.processItemOnOut(item, opt));
653
- });
564
+ async afterSet(items, opt) {
565
+ return items.map((item) => this.processItemOnOut(item, opt));
654
566
  }
655
- beforeRemove(params, opt) {
656
- return __awaiter(this, void 0, void 0, function* () {
657
- return this.defaultAfterAndBefore(params, opt);
658
- });
567
+ async beforeRemove(params, opt) {
568
+ return this.defaultAfterAndBefore(params, opt);
659
569
  }
660
- afterRemove(items, opt) {
661
- return __awaiter(this, void 0, void 0, function* () {
662
- return items.map((item) => this.processItemOnOut(item, opt));
663
- });
570
+ async afterRemove(items, opt) {
571
+ return items.map((item) => this.processItemOnOut(item, opt));
664
572
  }
665
- beforeRemoveMany(params, opt) {
666
- return __awaiter(this, void 0, void 0, function* () {
667
- return this.defaultAfterAndBefore(params, opt);
668
- });
573
+ async beforeRemoveMany(params, opt) {
574
+ return this.defaultAfterAndBefore(params, opt);
669
575
  }
670
- afterRemoveMany(items, opt) {
671
- return __awaiter(this, void 0, void 0, function* () {
672
- return items.map((item) => this.processItemOnOut(item, opt));
673
- });
576
+ async afterRemoveMany(items, opt) {
577
+ return items.map((item) => this.processItemOnOut(item, opt));
674
578
  }
675
- onException(params, opt) {
676
- return __awaiter(this, void 0, void 0, function* () {
677
- return '';
678
- });
579
+ async onException(params, opt) {
580
+ return '';
679
581
  }
680
582
  /**
681
583
  * Returns JWT secret and its settings to verify received JWT token
682
584
  * @param params Object of parameters passed to the authenticate method
683
585
  * @returns Object with the jwtSecret and verifyTokenArgs
684
586
  */
685
- getJwtTokenSecretAndSettings(params) {
686
- return __awaiter(this, void 0, void 0, function* () {
687
- const { space } = this.getContext();
688
- return {
689
- jwtSecret: (space === null || space === void 0 ? void 0 : space.tokenSecret) || this.config.jwtSecret || '',
690
- verifyTokenArgs: this.config.verifyTokenArgs,
691
- };
692
- });
587
+ async getJwtTokenSecretAndSettings(params) {
588
+ const { space } = this.getContext();
589
+ return {
590
+ jwtSecret: space?.tokenSecret || this.config.jwtSecret || '',
591
+ verifyTokenArgs: this.config.verifyTokenArgs,
592
+ };
693
593
  }
694
- findSpace() {
695
- return __awaiter(this, void 0, void 0, function* () {
696
- const { context } = this.config;
697
- if (context.space) {
698
- return [true, context.space];
594
+ async findSpace() {
595
+ const { context } = this.config;
596
+ if (context.space) {
597
+ return [true, context.space];
598
+ }
599
+ let space = null;
600
+ if (context.spaceGw) {
601
+ if (!context.spaceId) {
602
+ return [false, 'Space not specified'];
699
603
  }
700
- let space = null;
701
- if (context.spaceGw) {
702
- if (!context.spaceId) {
703
- return [false, 'Space not specified'];
704
- }
705
- // Lookup space in case we have gateway
706
- space = yield context.spaceGw.get(context.spaceId || '');
707
- if (!space) {
708
- return [false, 'Space not found'];
709
- }
710
- context.space = space;
604
+ // Lookup space in case we have gateway
605
+ space = await context.spaceGw.get(context.spaceId || '');
606
+ if (!space) {
607
+ return [false, 'Space not found'];
711
608
  }
712
- return [true, space];
713
- });
609
+ context.space = space;
610
+ }
611
+ return [true, space];
612
+ }
613
+ async extractCredentials(args) {
614
+ const { req, space, authorization } = args;
615
+ const token = req.cookies?.[space.cookieName] || authorization;
616
+ const fingerprint = req.cookies?.[space.fingerprintCookieName] || args.fingerprint || '';
617
+ return {
618
+ token,
619
+ fingerprint,
620
+ };
714
621
  }
715
- extractCredentials(args) {
716
- return __awaiter(this, void 0, void 0, function* () {
717
- var _a, _b;
718
- const { req, space, authorization } = args;
719
- const token = ((_a = req.cookies) === null || _a === void 0 ? void 0 : _a[space.cookieName]) || authorization;
720
- const fingerprint = ((_b = req.cookies) === null || _b === void 0 ? void 0 : _b[space.fingerprintCookieName]) || args.fingerprint || '';
721
- return {
722
- token,
622
+ async authenticate(params, opt) {
623
+ //const { accessRights } = params || {};
624
+ const context = this.getContext();
625
+ const { req, authorization } = context;
626
+ let authByToken = false;
627
+ const [spaceResult, space] = await this.findSpace();
628
+ if (spaceResult !== true) {
629
+ return [spaceResult, space];
630
+ }
631
+ const { token, fingerprint } = await this.extractCredentials({
632
+ req,
633
+ authorization,
634
+ fingerprint: context.fingerprint,
635
+ space,
636
+ params,
637
+ });
638
+ const { jwtSecret, verifyTokenArgs } = await this.getJwtTokenSecretAndSettings(params);
639
+ if (token && jwtSecret) {
640
+ const verifyResult = (0, userToken_1.verifyUserToken)(token, jwtSecret, {
641
+ ...verifyTokenArgs,
642
+ algorithms: verifyTokenArgs?.algorithms || [(0, userToken_1.getDefaultJwtAlgorithm)()],
643
+ audience: verifyTokenArgs?.audience || space.id,
644
+ issuer: verifyTokenArgs?.issuer || (0, userToken_1.getDefaultJwtIssuer)(),
723
645
  fingerprint,
724
- };
725
- });
726
- }
727
- authenticate(params, opt) {
728
- return __awaiter(this, void 0, void 0, function* () {
729
- //const { accessRights } = params || {};
730
- const context = this.getContext();
731
- const { req, authorization } = context;
732
- let authByToken = false;
733
- const [spaceResult, space] = yield this.findSpace();
734
- if (spaceResult !== true) {
735
- return [spaceResult, space];
736
- }
737
- const { token, fingerprint } = yield this.extractCredentials({
738
- req,
739
- authorization,
740
- fingerprint: context.fingerprint,
741
- space,
742
- params,
743
646
  });
744
- const { jwtSecret, verifyTokenArgs } = yield this.getJwtTokenSecretAndSettings(params);
745
- if (token && jwtSecret) {
746
- const verifyResult = (0, userToken_1.verifyUserToken)(token, jwtSecret, Object.assign(Object.assign({}, verifyTokenArgs), { algorithms: (verifyTokenArgs === null || verifyTokenArgs === void 0 ? void 0 : verifyTokenArgs.algorithms) || [(0, userToken_1.getDefaultJwtAlgorithm)()], audience: (verifyTokenArgs === null || verifyTokenArgs === void 0 ? void 0 : verifyTokenArgs.audience) || space.id, issuer: (verifyTokenArgs === null || verifyTokenArgs === void 0 ? void 0 : verifyTokenArgs.issuer) || (0, userToken_1.getDefaultJwtIssuer)(), fingerprint }));
747
- if (verifyResult.didFail()) {
748
- return [false, verifyResult.getErrorSummary('')];
749
- }
750
- const tokenData = verifyResult.getDataFirst();
751
- context.accountId = tokenData.accountId;
752
- context.roleId = tokenData.roleId;
753
- context.userId = tokenData.userId;
754
- context.isSuperAdmin = context.roleId === 'superadmin';
755
- context.spaceId = context.spaceId || tokenData.spaceId;
756
- context.lang = context.requestedLang || tokenData.lang;
757
- authByToken = true;
647
+ if (verifyResult.didFail()) {
648
+ return [false, verifyResult.getErrorSummary('')];
758
649
  }
759
- if (!authByToken) {
760
- if (this.config.interserviceApiKey && context.apiKey === this.config.interserviceApiKey) {
761
- return [true, ''];
762
- }
763
- else if ((space === null || space === void 0 ? void 0 : space.apiKey) && (space === null || space === void 0 ? void 0 : space.apiKey) !== context.apiKey) {
764
- return [false, 'API Key is invalid'];
765
- }
650
+ const tokenData = verifyResult.getDataFirst();
651
+ context.accountId = tokenData.accountId;
652
+ context.roleId = tokenData.roleId;
653
+ context.userId = tokenData.userId;
654
+ context.isSuperAdmin = context.roleId === 'superadmin';
655
+ context.spaceId = context.spaceId || tokenData.spaceId;
656
+ context.lang = context.requestedLang || tokenData.lang;
657
+ authByToken = true;
658
+ }
659
+ if (!authByToken) {
660
+ if (this.config.interserviceApiKey && context.apiKey === this.config.interserviceApiKey) {
661
+ return [true, ''];
766
662
  }
767
- return [true, ''];
768
- });
663
+ else if (space?.apiKey && space?.apiKey !== context.apiKey) {
664
+ return [false, 'API Key is invalid'];
665
+ }
666
+ }
667
+ return [true, ''];
769
668
  }
770
669
  processRemovedRecord(record) {
771
670
  if (record && typeof record.id === 'string') {
@@ -784,33 +683,30 @@ class BaseCore {
784
683
  });
785
684
  return obj;
786
685
  }
787
- setOrderNo(args) {
788
- return __awaiter(this, void 0, void 0, function* () {
789
- var _a;
790
- const { params, filter, gateway } = args || {};
791
- if (typeof params !== 'object') {
792
- throw new Error(`The 'setOrderNo' expected the parameter to have 'params' object but got: ${JSON.stringify(params)} `);
793
- }
794
- if (typeof gateway !== 'object') {
795
- throw new Error(`The 'setOrderNo' expected the parameter to have 'gateway' object but got: ${JSON.stringify(gateway)} `);
796
- }
797
- if (typeof gateway.list !== 'function') {
798
- throw new Error(`The 'setOrderNo' expected the 'gateway' object to have 'list' method but got: ${JSON.stringify(gateway.list)} `);
799
- }
800
- if (!params.orderNo) {
801
- const lastRecord = yield gateway.list({
802
- params: filter,
803
- pagination: { pageSize: 1, sortBy: [{ name: constants_1.FIELDS.ORDER_NO, order: constants_1.ORDER_BYS.DESC }] },
686
+ async setOrderNo(args) {
687
+ const { params, filter, gateway } = args || {};
688
+ if (typeof params !== 'object') {
689
+ throw new Error(`The 'setOrderNo' expected the parameter to have 'params' object but got: ${JSON.stringify(params)} `);
690
+ }
691
+ if (typeof gateway !== 'object') {
692
+ throw new Error(`The 'setOrderNo' expected the parameter to have 'gateway' object but got: ${JSON.stringify(gateway)} `);
693
+ }
694
+ if (typeof gateway.list !== 'function') {
695
+ throw new Error(`The 'setOrderNo' expected the 'gateway' object to have 'list' method but got: ${JSON.stringify(gateway.list)} `);
696
+ }
697
+ if (!params.orderNo) {
698
+ const lastRecord = await gateway.list({
699
+ params: filter,
700
+ pagination: { pageSize: 1, sortBy: [{ name: constants_1.FIELDS.ORDER_NO, order: constants_1.ORDER_BYS.DESC }] },
701
+ });
702
+ if (lastRecord.length > 0) {
703
+ const order = new utils_1.StrOrderHelpers({
704
+ start: lastRecord[0]?.orderNo || constants_1.DEFAULT_ORDER_NO,
705
+ step: constants_1.DEFAULT_ORDER_NO_STEP,
804
706
  });
805
- if (lastRecord.length > 0) {
806
- const order = new utils_1.StrOrderHelpers({
807
- start: ((_a = lastRecord[0]) === null || _a === void 0 ? void 0 : _a.orderNo) || constants_1.DEFAULT_ORDER_NO,
808
- step: constants_1.DEFAULT_ORDER_NO_STEP,
809
- });
810
- params.orderNo = order.increase();
811
- }
707
+ params.orderNo = order.increase();
812
708
  }
813
- });
709
+ }
814
710
  }
815
711
  }
816
712
  exports.BaseCore = BaseCore;