@sdflc/backend-helpers 1.0.78 → 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 (123) hide show
  1. package/build/BaseCore.js +496 -603
  2. package/build/BaseGateway.js +331 -379
  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 -189
  7. package/build/apiContext.js +35 -33
  8. package/build/baseController.js +9 -16
  9. package/build/commonValidators.js +22 -37
  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.d.ts +88 -0
  16. package/build/esm/BaseCore.js +706 -0
  17. package/build/esm/BaseGateway.d.ts +49 -0
  18. package/build/esm/BaseGateway.js +430 -0
  19. package/build/esm/DataCache.d.ts +14 -0
  20. package/build/esm/DataCache.js +95 -0
  21. package/build/esm/Database.d.ts +32 -0
  22. package/build/esm/Database.js +173 -0
  23. package/build/esm/DbMigratorAndSeeder.d.ts +49 -0
  24. package/build/esm/DbMigratorAndSeeder.js +173 -0
  25. package/build/esm/RedisDataLoader.d.ts +41 -0
  26. package/build/esm/RedisDataLoader.js +206 -0
  27. package/build/esm/apiContext.d.ts +11 -0
  28. package/build/esm/apiContext.js +137 -0
  29. package/build/esm/baseController.d.ts +17 -0
  30. package/build/esm/baseController.js +53 -0
  31. package/build/esm/checkItHelpers.d.ts +3 -0
  32. package/build/esm/checkItHelpers.js +23 -0
  33. package/build/esm/commonValidators.d.ts +17 -0
  34. package/build/esm/commonValidators.js +264 -0
  35. package/build/esm/configBulder.d.ts +2 -0
  36. package/build/esm/configBulder.js +32 -0
  37. package/build/esm/constants.d.ts +30 -0
  38. package/build/esm/constants.js +69 -0
  39. package/build/esm/dbHelpers.d.ts +43 -0
  40. package/build/esm/dbHelpers.js +144 -0
  41. package/build/esm/dbSeeder.d.ts +2 -0
  42. package/build/esm/dbSeeder.js +44 -0
  43. package/build/esm/dbTableHelpers.d.ts +11 -0
  44. package/build/esm/dbTableHelpers.js +99 -0
  45. package/build/esm/downloadHelpers.d.ts +2 -0
  46. package/build/esm/downloadHelpers.js +66 -0
  47. package/build/esm/index.d.ts +21 -0
  48. package/build/esm/index.js +21 -0
  49. package/build/esm/interfaces/ApiContext.d.ts +24 -0
  50. package/build/esm/interfaces/ApiContext.js +1 -0
  51. package/build/esm/interfaces/ApiContextInterface.d.ts +12 -0
  52. package/build/esm/interfaces/ApiContextInterface.js +1 -0
  53. package/build/esm/interfaces/BaseCoreActionsInterface.d.ts +38 -0
  54. package/build/esm/interfaces/BaseCoreActionsInterface.js +1 -0
  55. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +12 -0
  56. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.js +1 -0
  57. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +13 -0
  58. package/build/esm/interfaces/BaseCoreDoingWhatInterface.js +1 -0
  59. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +36 -0
  60. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  61. package/build/esm/interfaces/BaseCoreValidatorsInterface.d.ts +13 -0
  62. package/build/esm/interfaces/BaseCoreValidatorsInterface.js +1 -0
  63. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +39 -0
  64. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  65. package/build/esm/interfaces/BuildConfigOptions.d.ts +6 -0
  66. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  67. package/build/esm/interfaces/BuildDefaultResolversOptions.d.ts +17 -0
  68. package/build/esm/interfaces/BuildDefaultResolversOptions.js +1 -0
  69. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +6 -0
  70. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  71. package/build/esm/interfaces/CacheInterface.d.ts +15 -0
  72. package/build/esm/interfaces/CacheInterface.js +1 -0
  73. package/build/esm/interfaces/CommonValidatorArgs.d.ts +3 -0
  74. package/build/esm/interfaces/CommonValidatorArgs.js +1 -0
  75. package/build/esm/interfaces/CoreActionInterface.d.ts +14 -0
  76. package/build/esm/interfaces/CoreActionInterface.js +1 -0
  77. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +11 -0
  78. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  79. package/build/esm/interfaces/CreateUserTokenResult.d.ts +4 -0
  80. package/build/esm/interfaces/CreateUserTokenResult.js +1 -0
  81. package/build/esm/interfaces/DatabaseOptions.d.ts +22 -0
  82. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  83. package/build/esm/interfaces/DatabaseReadInterface.d.ts +14 -0
  84. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  85. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +9 -0
  86. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  87. package/build/esm/interfaces/DownloadFileArgs.d.ts +6 -0
  88. package/build/esm/interfaces/DownloadFileArgs.js +1 -0
  89. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +19 -0
  90. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  91. package/build/esm/interfaces/JwtTokenSecretAndSettings.d.ts +5 -0
  92. package/build/esm/interfaces/JwtTokenSecretAndSettings.js +1 -0
  93. package/build/esm/interfaces/ListArgsInterface.d.ts +5 -0
  94. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  95. package/build/esm/interfaces/LoaderInterface.d.ts +4 -0
  96. package/build/esm/interfaces/LoaderInterface.js +1 -0
  97. package/build/esm/interfaces/PaginationInterface.d.ts +7 -0
  98. package/build/esm/interfaces/PaginationInterface.js +1 -0
  99. package/build/esm/interfaces/SortItemInterface.d.ts +4 -0
  100. package/build/esm/interfaces/SortItemInterface.js +1 -0
  101. package/build/esm/interfaces/UserTokenParams.d.ts +8 -0
  102. package/build/esm/interfaces/UserTokenParams.js +1 -0
  103. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +13 -0
  104. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  105. package/build/esm/interfaces/index.d.ts +28 -0
  106. package/build/esm/interfaces/index.js +27 -0
  107. package/build/esm/knexConfigBuilder.d.ts +1 -0
  108. package/build/esm/knexConfigBuilder.js +83 -0
  109. package/build/esm/passwordHelpers.d.ts +5 -0
  110. package/build/esm/passwordHelpers.js +13 -0
  111. package/build/esm/redisClient.d.ts +17 -0
  112. package/build/esm/redisClient.js +94 -0
  113. package/build/esm/resolversHelpers.d.ts +3 -0
  114. package/build/esm/resolversHelpers.js +66 -0
  115. package/build/esm/userToken.d.ts +8 -0
  116. package/build/esm/userToken.js +74 -0
  117. package/build/esm/utils.d.ts +2 -0
  118. package/build/esm/utils.js +13 -0
  119. package/build/knexConfigBuilder.js +17 -7
  120. package/build/passwordHelpers.js +7 -16
  121. package/build/resolversHelpers.js +11 -4
  122. package/build/userToken.js +2 -2
  123. package/package.json +13 -6
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,193 +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
- // eslint-disable-next-line
548
- defaultAfterAndBefore(params, opt) {
549
- return __awaiter(this, void 0, void 0, function* () {
550
- return params;
551
- });
493
+ async defaultAfterAndBefore(params, opt) {
494
+ return params;
552
495
  }
553
496
  /**
554
497
  * Used to transform an object before sending it in the response
@@ -568,207 +511,160 @@ class BaseCore {
568
511
  processItemOnIn(item, opt) {
569
512
  return this.defaultAfterAndBefore(item, opt);
570
513
  }
571
- beforeGet(item, opt) {
572
- return __awaiter(this, void 0, void 0, function* () {
573
- return this.defaultAfterAndBefore(item, opt);
574
- });
514
+ async beforeGet(item, opt) {
515
+ return this.defaultAfterAndBefore(item, opt);
575
516
  }
576
- beforeGetMany(items, opt) {
577
- return __awaiter(this, void 0, void 0, function* () {
578
- return this.defaultAfterAndBefore(items, opt);
579
- });
517
+ async beforeGetMany(items, opt) {
518
+ return this.defaultAfterAndBefore(items, opt);
580
519
  }
581
- beforeList(filter, opt) {
582
- return __awaiter(this, void 0, void 0, function* () {
583
- return this.defaultAfterAndBefore(filter, opt);
584
- });
520
+ async beforeList(filter, opt) {
521
+ return this.defaultAfterAndBefore(filter, opt);
585
522
  }
586
- afterGet(item, opt) {
587
- return __awaiter(this, void 0, void 0, function* () {
588
- return this.processItemOnOut(item, opt);
589
- });
523
+ async afterGet(item, opt) {
524
+ return this.processItemOnOut(item, opt);
590
525
  }
591
- afterGetMany(items, opt) {
592
- return __awaiter(this, void 0, void 0, function* () {
593
- return items.map((item) => this.processItemOnOut(item, opt));
594
- });
526
+ async afterGetMany(items, opt) {
527
+ return items.map((item) => this.processItemOnOut(item, opt));
595
528
  }
596
- afterList(items, opt) {
597
- return __awaiter(this, void 0, void 0, function* () {
598
- return items.map((item) => this.processItemOnOut(item, opt));
599
- });
529
+ async afterList(items, opt) {
530
+ return items.map((item) => this.processItemOnOut(item, opt));
600
531
  }
601
- beforeCreate(params, opt) {
602
- return __awaiter(this, void 0, void 0, function* () {
603
- return this.processItemOnIn(params, opt);
604
- });
532
+ async beforeCreate(params, opt) {
533
+ return this.processItemOnIn(params, opt);
605
534
  }
606
- afterCreate(items, opt) {
607
- return __awaiter(this, void 0, void 0, function* () {
608
- return items.map((item) => this.processItemOnOut(item, opt));
609
- });
535
+ async afterCreate(items, opt) {
536
+ return items.map((item) => this.processItemOnOut(item, opt));
610
537
  }
611
- beforeCreateMany(items, opt) {
612
- return __awaiter(this, void 0, void 0, function* () {
613
- return items.map((item) => this.processItemOnIn(item, opt));
614
- });
538
+ async beforeCreateMany(items, opt) {
539
+ return items.map((item) => this.processItemOnIn(item, opt));
615
540
  }
616
- afterCreateMany(items, opt) {
617
- return __awaiter(this, void 0, void 0, function* () {
618
- return items.map((item) => this.processItemOnOut(item, opt));
619
- });
541
+ async afterCreateMany(items, opt) {
542
+ return items.map((item) => this.processItemOnOut(item, opt));
620
543
  }
621
- beforeUpdate(params, opt) {
622
- return __awaiter(this, void 0, void 0, function* () {
623
- return this.processItemOnIn(params, opt);
624
- });
544
+ async beforeUpdate(params, opt) {
545
+ return this.processItemOnIn(params, opt);
625
546
  }
626
- afterUpdate(items, opt) {
627
- return __awaiter(this, void 0, void 0, function* () {
628
- return items.map((item) => this.processItemOnOut(item, opt));
629
- });
547
+ async afterUpdate(items, opt) {
548
+ return items.map((item) => this.processItemOnOut(item, opt));
630
549
  }
631
- beforeUpdateMany(items, opt) {
632
- return __awaiter(this, void 0, void 0, function* () {
633
- return items.map((item) => {
634
- return {
635
- params: this.processItemOnIn(item.params, opt),
636
- where: item.where,
637
- };
638
- });
550
+ async beforeUpdateMany(items, opt) {
551
+ return items.map((item) => {
552
+ return {
553
+ params: this.processItemOnIn(item.params, opt),
554
+ where: item.where,
555
+ };
639
556
  });
640
557
  }
641
- afterUpdateMany(items, opt) {
642
- return __awaiter(this, void 0, void 0, function* () {
643
- return items.map((item) => this.processItemOnOut(item, opt));
644
- });
558
+ async afterUpdateMany(items, opt) {
559
+ return items.map((item) => this.processItemOnOut(item, opt));
645
560
  }
646
- beforeSet(params, opt) {
647
- return __awaiter(this, void 0, void 0, function* () {
648
- return (0, lodash_1.castArray)(params).map((item) => this.processItemOnIn(item, opt));
649
- });
561
+ async beforeSet(params, opt) {
562
+ return (0, lodash_1.castArray)(params).map((item) => this.processItemOnIn(item, opt));
650
563
  }
651
- afterSet(items, opt) {
652
- return __awaiter(this, void 0, void 0, function* () {
653
- return items.map((item) => this.processItemOnOut(item, opt));
654
- });
564
+ async afterSet(items, opt) {
565
+ return items.map((item) => this.processItemOnOut(item, opt));
655
566
  }
656
- beforeRemove(params, opt) {
657
- return __awaiter(this, void 0, void 0, function* () {
658
- return this.defaultAfterAndBefore(params, opt);
659
- });
567
+ async beforeRemove(params, opt) {
568
+ return this.defaultAfterAndBefore(params, opt);
660
569
  }
661
- afterRemove(items, opt) {
662
- return __awaiter(this, void 0, void 0, function* () {
663
- return items.map((item) => this.processItemOnOut(item, opt));
664
- });
570
+ async afterRemove(items, opt) {
571
+ return items.map((item) => this.processItemOnOut(item, opt));
665
572
  }
666
- beforeRemoveMany(params, opt) {
667
- return __awaiter(this, void 0, void 0, function* () {
668
- return this.defaultAfterAndBefore(params, opt);
669
- });
573
+ async beforeRemoveMany(params, opt) {
574
+ return this.defaultAfterAndBefore(params, opt);
670
575
  }
671
- afterRemoveMany(items, opt) {
672
- return __awaiter(this, void 0, void 0, function* () {
673
- return items.map((item) => this.processItemOnOut(item, opt));
674
- });
576
+ async afterRemoveMany(items, opt) {
577
+ return items.map((item) => this.processItemOnOut(item, opt));
675
578
  }
676
- onException(params, opt) {
677
- return __awaiter(this, void 0, void 0, function* () {
678
- return '';
679
- });
579
+ async onException(params, opt) {
580
+ return '';
680
581
  }
681
582
  /**
682
583
  * Returns JWT secret and its settings to verify received JWT token
683
584
  * @param params Object of parameters passed to the authenticate method
684
585
  * @returns Object with the jwtSecret and verifyTokenArgs
685
586
  */
686
- // eslint-disable-next-line
687
- getJwtTokenSecretAndSettings(params) {
688
- return __awaiter(this, void 0, void 0, function* () {
689
- const { space } = this.getContext();
690
- return {
691
- jwtSecret: (space === null || space === void 0 ? void 0 : space.tokenSecret) || this.config.jwtSecret || '',
692
- verifyTokenArgs: this.config.verifyTokenArgs,
693
- };
694
- });
587
+ async getJwtTokenSecretAndSettings(params) {
588
+ const { space } = this.getContext();
589
+ return {
590
+ jwtSecret: space?.tokenSecret || this.config.jwtSecret || '',
591
+ verifyTokenArgs: this.config.verifyTokenArgs,
592
+ };
695
593
  }
696
- findSpace() {
697
- return __awaiter(this, void 0, void 0, function* () {
698
- const { context } = this.config;
699
- if (context.space) {
700
- 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'];
701
603
  }
702
- let space = null;
703
- if (context.spaceGw) {
704
- if (!context.spaceId) {
705
- return [false, 'Space not specified'];
706
- }
707
- // Lookup space in case we have gateway
708
- space = yield context.spaceGw.get(context.spaceId || '');
709
- if (!space) {
710
- return [false, 'Space not found'];
711
- }
712
- 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'];
713
608
  }
714
- return [true, space];
715
- });
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
+ };
716
621
  }
717
- extractCredentials(args) {
718
- return __awaiter(this, void 0, void 0, function* () {
719
- var _a, _b;
720
- const { req, space, authorization } = args;
721
- const token = ((_a = req.cookies) === null || _a === void 0 ? void 0 : _a[space.cookieName]) || authorization;
722
- const fingerprint = ((_b = req.cookies) === null || _b === void 0 ? void 0 : _b[space.fingerprintCookieName]) || args.fingerprint || '';
723
- return {
724
- 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)(),
725
645
  fingerprint,
726
- };
727
- });
728
- }
729
- // eslint-disable-next-line
730
- authenticate(params, opt) {
731
- return __awaiter(this, void 0, void 0, function* () {
732
- //const { accessRights } = params || {};
733
- const context = this.getContext();
734
- const { req, authorization } = context;
735
- let authByToken = false;
736
- const [spaceResult, space] = yield this.findSpace();
737
- if (spaceResult !== true) {
738
- return [spaceResult, space];
739
- }
740
- const { token, fingerprint } = yield this.extractCredentials({
741
- req,
742
- authorization,
743
- fingerprint: context.fingerprint,
744
- space,
745
- params,
746
646
  });
747
- const { jwtSecret, verifyTokenArgs } = yield this.getJwtTokenSecretAndSettings(params);
748
- if (token && jwtSecret) {
749
- 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 }));
750
- if (verifyResult.didFail()) {
751
- return [false, verifyResult.getErrorSummary('')];
752
- }
753
- const tokenData = verifyResult.getDataFirst();
754
- context.accountId = tokenData.accountId;
755
- context.roleId = tokenData.roleId;
756
- context.userId = tokenData.userId;
757
- context.isSuperAdmin = context.roleId === 'superadmin';
758
- context.spaceId = context.spaceId || tokenData.spaceId;
759
- context.lang = context.requestedLang || tokenData.lang;
760
- authByToken = true;
647
+ if (verifyResult.didFail()) {
648
+ return [false, verifyResult.getErrorSummary('')];
761
649
  }
762
- if (!authByToken) {
763
- if (this.config.interserviceApiKey && context.apiKey === this.config.interserviceApiKey) {
764
- return [true, ''];
765
- }
766
- else if ((space === null || space === void 0 ? void 0 : space.apiKey) && (space === null || space === void 0 ? void 0 : space.apiKey) !== context.apiKey) {
767
- return [false, 'API Key is invalid'];
768
- }
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, ''];
769
662
  }
770
- return [true, ''];
771
- });
663
+ else if (space?.apiKey && space?.apiKey !== context.apiKey) {
664
+ return [false, 'API Key is invalid'];
665
+ }
666
+ }
667
+ return [true, ''];
772
668
  }
773
669
  processRemovedRecord(record) {
774
670
  if (record && typeof record.id === 'string') {
@@ -787,33 +683,30 @@ class BaseCore {
787
683
  });
788
684
  return obj;
789
685
  }
790
- setOrderNo(args) {
791
- return __awaiter(this, void 0, void 0, function* () {
792
- var _a;
793
- const { params, filter, gateway } = args || {};
794
- if (typeof params !== 'object') {
795
- throw new Error(`The 'setOrderNo' expected the parameter to have 'params' object but got: ${JSON.stringify(params)} `);
796
- }
797
- if (typeof gateway !== 'object') {
798
- throw new Error(`The 'setOrderNo' expected the parameter to have 'gateway' object but got: ${JSON.stringify(gateway)} `);
799
- }
800
- if (typeof gateway.list !== 'function') {
801
- throw new Error(`The 'setOrderNo' expected the 'gateway' object to have 'list' method but got: ${JSON.stringify(gateway.list)} `);
802
- }
803
- if (!params.orderNo) {
804
- const lastRecord = yield gateway.list({
805
- params: filter,
806
- 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,
807
706
  });
808
- if (lastRecord.length > 0) {
809
- const order = new utils_1.StrOrderHelpers({
810
- start: ((_a = lastRecord[0]) === null || _a === void 0 ? void 0 : _a.orderNo) || constants_1.DEFAULT_ORDER_NO,
811
- step: constants_1.DEFAULT_ORDER_NO_STEP,
812
- });
813
- params.orderNo = order.increase();
814
- }
707
+ params.orderNo = order.increase();
815
708
  }
816
- });
709
+ }
817
710
  }
818
711
  }
819
712
  exports.BaseCore = BaseCore;