@sdflc/backend-helpers 1.0.105 → 1.0.106

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 (209) hide show
  1. package/package.json +25 -25
  2. package/build/BaseCore.d.ts +0 -88
  3. package/build/BaseCore.js +0 -723
  4. package/build/BaseGateway.d.ts +0 -56
  5. package/build/BaseGateway.js +0 -480
  6. package/build/DataCache.d.ts +0 -16
  7. package/build/DataCache.js +0 -112
  8. package/build/Database.d.ts +0 -36
  9. package/build/Database.js +0 -195
  10. package/build/DbMigratorAndSeeder.d.ts +0 -49
  11. package/build/DbMigratorAndSeeder.js +0 -212
  12. package/build/RedisDataLoader.d.ts +0 -41
  13. package/build/RedisDataLoader.js +0 -212
  14. package/build/apiContext.d.ts +0 -11
  15. package/build/apiContext.js +0 -146
  16. package/build/baseController.d.ts +0 -17
  17. package/build/baseController.js +0 -59
  18. package/build/checkItHelpers.d.ts +0 -3
  19. package/build/checkItHelpers.js +0 -28
  20. package/build/commonValidators.d.ts +0 -17
  21. package/build/commonValidators.js +0 -311
  22. package/build/configBulder.d.ts +0 -2
  23. package/build/configBulder.js +0 -36
  24. package/build/constants.d.ts +0 -30
  25. package/build/constants.js +0 -80
  26. package/build/dbHelpers.d.ts +0 -43
  27. package/build/dbHelpers.js +0 -156
  28. package/build/dbSeeder.d.ts +0 -2
  29. package/build/dbSeeder.js +0 -83
  30. package/build/dbTableHelpers.d.ts +0 -14
  31. package/build/dbTableHelpers.js +0 -118
  32. package/build/downloadHelpers.d.ts +0 -2
  33. package/build/downloadHelpers.js +0 -73
  34. package/build/esm/BaseCore.d.ts +0 -88
  35. package/build/esm/BaseCore.js +0 -717
  36. package/build/esm/BaseGateway.d.ts +0 -56
  37. package/build/esm/BaseGateway.js +0 -474
  38. package/build/esm/DataCache.d.ts +0 -16
  39. package/build/esm/DataCache.js +0 -106
  40. package/build/esm/Database.d.ts +0 -36
  41. package/build/esm/Database.js +0 -189
  42. package/build/esm/DbMigratorAndSeeder.d.ts +0 -49
  43. package/build/esm/DbMigratorAndSeeder.js +0 -173
  44. package/build/esm/RedisDataLoader.d.ts +0 -41
  45. package/build/esm/RedisDataLoader.js +0 -206
  46. package/build/esm/apiContext.d.ts +0 -11
  47. package/build/esm/apiContext.js +0 -138
  48. package/build/esm/baseController.d.ts +0 -17
  49. package/build/esm/baseController.js +0 -53
  50. package/build/esm/checkItHelpers.d.ts +0 -3
  51. package/build/esm/checkItHelpers.js +0 -23
  52. package/build/esm/commonValidators.d.ts +0 -17
  53. package/build/esm/commonValidators.js +0 -291
  54. package/build/esm/configBulder.d.ts +0 -2
  55. package/build/esm/configBulder.js +0 -32
  56. package/build/esm/constants.d.ts +0 -30
  57. package/build/esm/constants.js +0 -69
  58. package/build/esm/dbHelpers.d.ts +0 -43
  59. package/build/esm/dbHelpers.js +0 -144
  60. package/build/esm/dbSeeder.d.ts +0 -2
  61. package/build/esm/dbSeeder.js +0 -44
  62. package/build/esm/dbTableHelpers.d.ts +0 -14
  63. package/build/esm/dbTableHelpers.js +0 -106
  64. package/build/esm/downloadHelpers.d.ts +0 -2
  65. package/build/esm/downloadHelpers.js +0 -66
  66. package/build/esm/index.d.ts +0 -21
  67. package/build/esm/index.js +0 -21
  68. package/build/esm/interfaces/ApiContext.d.ts +0 -25
  69. package/build/esm/interfaces/ApiContext.js +0 -1
  70. package/build/esm/interfaces/ApiContextInterface.d.ts +0 -12
  71. package/build/esm/interfaces/ApiContextInterface.js +0 -1
  72. package/build/esm/interfaces/BaseCoreActionsInterface.d.ts +0 -38
  73. package/build/esm/interfaces/BaseCoreActionsInterface.js +0 -1
  74. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +0 -12
  75. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.js +0 -1
  76. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +0 -13
  77. package/build/esm/interfaces/BaseCoreDoingWhatInterface.js +0 -1
  78. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +0 -37
  79. package/build/esm/interfaces/BaseCorePropsInterface.js +0 -1
  80. package/build/esm/interfaces/BaseCoreValidatorsInterface.d.ts +0 -13
  81. package/build/esm/interfaces/BaseCoreValidatorsInterface.js +0 -1
  82. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +0 -39
  83. package/build/esm/interfaces/BaseGatewayPropsInterface.js +0 -1
  84. package/build/esm/interfaces/BuildConfigOptions.d.ts +0 -6
  85. package/build/esm/interfaces/BuildConfigOptions.js +0 -1
  86. package/build/esm/interfaces/BuildDefaultResolversOptions.d.ts +0 -17
  87. package/build/esm/interfaces/BuildDefaultResolversOptions.js +0 -1
  88. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +0 -6
  89. package/build/esm/interfaces/BuildListQueryArgsInterface.js +0 -1
  90. package/build/esm/interfaces/CacheInterface.d.ts +0 -15
  91. package/build/esm/interfaces/CacheInterface.js +0 -1
  92. package/build/esm/interfaces/CommonValidatorArgs.d.ts +0 -3
  93. package/build/esm/interfaces/CommonValidatorArgs.js +0 -1
  94. package/build/esm/interfaces/CoreActionInterface.d.ts +0 -14
  95. package/build/esm/interfaces/CoreActionInterface.js +0 -1
  96. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +0 -11
  97. package/build/esm/interfaces/CreateUserTokenArgs.js +0 -1
  98. package/build/esm/interfaces/CreateUserTokenResult.d.ts +0 -4
  99. package/build/esm/interfaces/CreateUserTokenResult.js +0 -1
  100. package/build/esm/interfaces/DatabaseOptions.d.ts +0 -26
  101. package/build/esm/interfaces/DatabaseOptions.js +0 -1
  102. package/build/esm/interfaces/DatabaseReadInterface.d.ts +0 -14
  103. package/build/esm/interfaces/DatabaseReadInterface.js +0 -1
  104. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +0 -9
  105. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +0 -1
  106. package/build/esm/interfaces/DownloadFileArgs.d.ts +0 -6
  107. package/build/esm/interfaces/DownloadFileArgs.js +0 -1
  108. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +0 -19
  109. package/build/esm/interfaces/ExtractCredentialsArgs.js +0 -1
  110. package/build/esm/interfaces/JwtTokenSecretAndSettings.d.ts +0 -5
  111. package/build/esm/interfaces/JwtTokenSecretAndSettings.js +0 -1
  112. package/build/esm/interfaces/ListArgsInterface.d.ts +0 -7
  113. package/build/esm/interfaces/ListArgsInterface.js +0 -1
  114. package/build/esm/interfaces/LoaderInterface.d.ts +0 -7
  115. package/build/esm/interfaces/LoaderInterface.js +0 -1
  116. package/build/esm/interfaces/PaginationInterface.d.ts +0 -10
  117. package/build/esm/interfaces/PaginationInterface.js +0 -1
  118. package/build/esm/interfaces/SortItemInterface.d.ts +0 -4
  119. package/build/esm/interfaces/SortItemInterface.js +0 -1
  120. package/build/esm/interfaces/UserTokenParams.d.ts +0 -8
  121. package/build/esm/interfaces/UserTokenParams.js +0 -1
  122. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +0 -13
  123. package/build/esm/interfaces/VerifyUserTokenArgs.js +0 -1
  124. package/build/esm/interfaces/index.d.ts +0 -28
  125. package/build/esm/interfaces/index.js +0 -27
  126. package/build/esm/knexConfigBuilder.d.ts +0 -1
  127. package/build/esm/knexConfigBuilder.js +0 -84
  128. package/build/esm/passwordHelpers.d.ts +0 -5
  129. package/build/esm/passwordHelpers.js +0 -13
  130. package/build/esm/redisClient.d.ts +0 -17
  131. package/build/esm/redisClient.js +0 -94
  132. package/build/esm/resolversHelpers.d.ts +0 -3
  133. package/build/esm/resolversHelpers.js +0 -66
  134. package/build/esm/userToken.d.ts +0 -8
  135. package/build/esm/userToken.js +0 -74
  136. package/build/esm/utils.d.ts +0 -2
  137. package/build/esm/utils.js +0 -13
  138. package/build/index.d.ts +0 -21
  139. package/build/index.js +0 -37
  140. package/build/interfaces/ApiContext.d.ts +0 -25
  141. package/build/interfaces/ApiContext.js +0 -2
  142. package/build/interfaces/ApiContextInterface.d.ts +0 -12
  143. package/build/interfaces/ApiContextInterface.js +0 -2
  144. package/build/interfaces/BaseCoreActionsInterface.d.ts +0 -38
  145. package/build/interfaces/BaseCoreActionsInterface.js +0 -2
  146. package/build/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +0 -12
  147. package/build/interfaces/BaseCoreDoAuthOnActionInterface.js +0 -2
  148. package/build/interfaces/BaseCoreDoingWhatInterface.d.ts +0 -13
  149. package/build/interfaces/BaseCoreDoingWhatInterface.js +0 -2
  150. package/build/interfaces/BaseCorePropsInterface.d.ts +0 -37
  151. package/build/interfaces/BaseCorePropsInterface.js +0 -2
  152. package/build/interfaces/BaseCoreValidatorsInterface.d.ts +0 -13
  153. package/build/interfaces/BaseCoreValidatorsInterface.js +0 -2
  154. package/build/interfaces/BaseGatewayPropsInterface.d.ts +0 -39
  155. package/build/interfaces/BaseGatewayPropsInterface.js +0 -2
  156. package/build/interfaces/BuildConfigOptions.d.ts +0 -6
  157. package/build/interfaces/BuildConfigOptions.js +0 -2
  158. package/build/interfaces/BuildDefaultResolversOptions.d.ts +0 -17
  159. package/build/interfaces/BuildDefaultResolversOptions.js +0 -2
  160. package/build/interfaces/BuildListQueryArgsInterface.d.ts +0 -6
  161. package/build/interfaces/BuildListQueryArgsInterface.js +0 -2
  162. package/build/interfaces/CacheInterface.d.ts +0 -15
  163. package/build/interfaces/CacheInterface.js +0 -2
  164. package/build/interfaces/CommonValidatorArgs.d.ts +0 -3
  165. package/build/interfaces/CommonValidatorArgs.js +0 -2
  166. package/build/interfaces/CoreActionInterface.d.ts +0 -14
  167. package/build/interfaces/CoreActionInterface.js +0 -2
  168. package/build/interfaces/CreateUserTokenArgs.d.ts +0 -11
  169. package/build/interfaces/CreateUserTokenArgs.js +0 -2
  170. package/build/interfaces/CreateUserTokenResult.d.ts +0 -4
  171. package/build/interfaces/CreateUserTokenResult.js +0 -2
  172. package/build/interfaces/DatabaseOptions.d.ts +0 -26
  173. package/build/interfaces/DatabaseOptions.js +0 -2
  174. package/build/interfaces/DatabaseReadInterface.d.ts +0 -14
  175. package/build/interfaces/DatabaseReadInterface.js +0 -2
  176. package/build/interfaces/DbFieldAddDefaultInterface.d.ts +0 -9
  177. package/build/interfaces/DbFieldAddDefaultInterface.js +0 -2
  178. package/build/interfaces/DownloadFileArgs.d.ts +0 -6
  179. package/build/interfaces/DownloadFileArgs.js +0 -2
  180. package/build/interfaces/ExtractCredentialsArgs.d.ts +0 -19
  181. package/build/interfaces/ExtractCredentialsArgs.js +0 -2
  182. package/build/interfaces/JwtTokenSecretAndSettings.d.ts +0 -5
  183. package/build/interfaces/JwtTokenSecretAndSettings.js +0 -2
  184. package/build/interfaces/ListArgsInterface.d.ts +0 -7
  185. package/build/interfaces/ListArgsInterface.js +0 -2
  186. package/build/interfaces/LoaderInterface.d.ts +0 -7
  187. package/build/interfaces/LoaderInterface.js +0 -2
  188. package/build/interfaces/PaginationInterface.d.ts +0 -10
  189. package/build/interfaces/PaginationInterface.js +0 -2
  190. package/build/interfaces/SortItemInterface.d.ts +0 -4
  191. package/build/interfaces/SortItemInterface.js +0 -2
  192. package/build/interfaces/UserTokenParams.d.ts +0 -8
  193. package/build/interfaces/UserTokenParams.js +0 -2
  194. package/build/interfaces/VerifyUserTokenArgs.d.ts +0 -13
  195. package/build/interfaces/VerifyUserTokenArgs.js +0 -2
  196. package/build/interfaces/index.d.ts +0 -28
  197. package/build/interfaces/index.js +0 -43
  198. package/build/knexConfigBuilder.d.ts +0 -1
  199. package/build/knexConfigBuilder.js +0 -91
  200. package/build/passwordHelpers.d.ts +0 -5
  201. package/build/passwordHelpers.js +0 -21
  202. package/build/redisClient.d.ts +0 -17
  203. package/build/redisClient.js +0 -97
  204. package/build/resolversHelpers.d.ts +0 -3
  205. package/build/resolversHelpers.js +0 -69
  206. package/build/userToken.d.ts +0 -8
  207. package/build/userToken.js +0 -86
  208. package/build/utils.d.ts +0 -2
  209. package/build/utils.js +0 -21
package/build/BaseCore.js DELETED
@@ -1,723 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.BaseCore = void 0;
7
- const api_helpers_1 = require("@sdflc/api-helpers");
8
- const utils_1 = require("@sdflc/utils");
9
- const check_types_1 = __importDefault(require("check-types"));
10
- const lodash_1 = require("lodash");
11
- const commonValidators_1 = require("./commonValidators");
12
- const constants_1 = require("./constants");
13
- const userToken_1 = require("./userToken");
14
- const defaultValidate = ( /*args: any, opt?: BaseCoreActionsInterface*/) => {
15
- return [true, {}];
16
- };
17
- const defaultMutationValidate = ( /*args: any, opt?: BaseCoreActionsInterface*/) => {
18
- return [true, {}];
19
- };
20
- const defaultValidators = {
21
- list: defaultValidate,
22
- get: commonValidators_1.validateGet,
23
- getMany: commonValidators_1.validateGetMany,
24
- create: defaultValidate,
25
- createMany: defaultValidate,
26
- update: defaultValidate,
27
- updateMany: defaultValidate,
28
- set: defaultValidate,
29
- remove: commonValidators_1.validateRemove,
30
- removeMany: commonValidators_1.validateRemoveMany,
31
- };
32
- class BaseCore {
33
- measureTool = new utils_1.MeasureTool();
34
- config;
35
- logger;
36
- constructor(props) {
37
- this.config = props || {};
38
- this.logger = this.config.logger instanceof utils_1.Logger ? this.config.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.ERROR });
39
- this.config.doAuthOnAction = {
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,
50
- };
51
- }
52
- getIdType() {
53
- return this.config.idType ?? constants_1.ID_TYPES.UNKNOWN;
54
- }
55
- getDb() {
56
- return this.config.db;
57
- }
58
- getRequestId() {
59
- return this.config.context.requestId;
60
- }
61
- getContext() {
62
- return this.config.context;
63
- }
64
- getGateways() {
65
- return this.config.context.gateways || {};
66
- }
67
- getGateway(name) {
68
- return this.getGateways()?.[name || this.config.gatewayName];
69
- }
70
- getValidators() {
71
- return defaultValidators;
72
- }
73
- success(data, code) {
74
- const code2use = code != null ? code : api_helpers_1.OP_RESULT_CODES.OK;
75
- let data2use = data;
76
- if (!Array.isArray(data2use)) {
77
- if (data) {
78
- data2use = [data];
79
- }
80
- else {
81
- data2use = [];
82
- }
83
- }
84
- return new api_helpers_1.OpResult({
85
- code: code2use,
86
- data: data2use,
87
- errors: [],
88
- }).toJS();
89
- }
90
- failure(code, errorMsg, data) {
91
- const result = new api_helpers_1.OpResult({ data });
92
- result.addError('', errorMsg, code);
93
- return result.toJS();
94
- }
95
- validationFailure(ex) {
96
- const result = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED });
97
- if (ex instanceof api_helpers_1.OpResult) {
98
- return result.toJS();
99
- }
100
- Object.keys(ex?.errors || {}).forEach((key) => {
101
- const obj = ex.errors[key];
102
- if (Array.isArray(obj.errors)) {
103
- // if we have multiple rules failures the add them all
104
- obj.errors.forEach((item) => {
105
- result.addError(key, item.message);
106
- });
107
- }
108
- else {
109
- result.addError(key, obj.message);
110
- }
111
- });
112
- return result.toJS();
113
- }
114
- exceptionFailure(ex, doingWhat, data) {
115
- const [isDbError, dbErrorMsg] = this.getDb().isDbError(ex);
116
- const isOpResult = typeof ex.getErrorSummary === 'function';
117
- const message = isOpResult ? ex.getErrorSummary() : ex.message;
118
- const sysMsg = `An exception has occurred on ${doingWhat} with message ${message}:`;
119
- let msg = '';
120
- if (isDbError) {
121
- msg = dbErrorMsg;
122
- }
123
- else {
124
- msg = isOpResult ? ex.getErrorSummary() : `Sorry, something went wrong on ${doingWhat}`;
125
- this.logger.error(sysMsg, ex);
126
- }
127
- const result = new api_helpers_1.OpResult({ data });
128
- result.addError('', msg, api_helpers_1.OP_RESULT_CODES.EXCEPTION);
129
- return result.toJS();
130
- }
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();
140
- }
141
- else {
142
- this.logger.debug(`Rollback DB transaction on ${doingWhat} as action result code is '${result.code}'`);
143
- await this.getDb().rollbackTransaction();
144
- }
145
- }
146
- }
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`);
169
- }
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
- }
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;
192
- }
193
- }
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;
203
- }
204
- }
205
- }
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] || {};
218
- }
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 });
226
- }
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 });
247
- }
248
- }
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
- }
262
- }
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',
331
- });
332
- }
333
- getGatewayToSetOrerNo() {
334
- return this.getContext().gateways[this.config.gatewayName];
335
- }
336
- getFilterToSetOrderNo(args) {
337
- return {};
338
- }
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
- await 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',
491
- });
492
- }
493
- async defaultAfterAndBefore(params, opt) {
494
- return params;
495
- }
496
- /**
497
- * Used to transform an object before sending it in the response
498
- * @param {any} item An object coming from the database
499
- * @param {BaseCoreActionsInterface} opt Options
500
- * @returns {any} transformed object
501
- */
502
- processItemOnOut(item, opt) {
503
- return this.defaultAfterAndBefore(item, opt);
504
- }
505
- /**
506
- * Used to transform an object before processing it on the request
507
- * @param {any} item An object coming from the outside
508
- * @param {BaseCoreActionsInterface} opt Options
509
- * @returns {any} transformed object
510
- */
511
- processItemOnIn(item, opt) {
512
- return this.defaultAfterAndBefore(item, opt);
513
- }
514
- async beforeGet(item, opt) {
515
- return this.defaultAfterAndBefore(item, opt);
516
- }
517
- async beforeGetMany(items, opt) {
518
- return this.defaultAfterAndBefore(items, opt);
519
- }
520
- async beforeList(filter, opt) {
521
- return this.defaultAfterAndBefore(filter, opt);
522
- }
523
- async afterGet(item, opt) {
524
- return this.processItemOnOut(item, opt);
525
- }
526
- async afterGetMany(items, opt) {
527
- return items.map((item) => this.processItemOnOut(item, opt));
528
- }
529
- async afterList(items, opt) {
530
- return items.map((item) => this.processItemOnOut(item, opt));
531
- }
532
- async beforeCreate(params, opt) {
533
- return this.processItemOnIn(params, opt);
534
- }
535
- async afterCreate(items, opt) {
536
- return items.map((item) => this.processItemOnOut(item, opt));
537
- }
538
- async beforeCreateMany(items, opt) {
539
- return items.map((item) => this.processItemOnIn(item, opt));
540
- }
541
- async afterCreateMany(items, opt) {
542
- return items.map((item) => this.processItemOnOut(item, opt));
543
- }
544
- async beforeUpdate(params, opt) {
545
- return this.processItemOnIn(params, opt);
546
- }
547
- async afterUpdate(items, opt) {
548
- return items.map((item) => this.processItemOnOut(item, opt));
549
- }
550
- async beforeUpdateMany(items, opt) {
551
- return items.map((item) => {
552
- return {
553
- params: this.processItemOnIn(item.params, opt),
554
- where: item.where,
555
- };
556
- });
557
- }
558
- async afterUpdateMany(items, opt) {
559
- return items.map((item) => this.processItemOnOut(item, opt));
560
- }
561
- async beforeSet(params, opt) {
562
- return (0, lodash_1.castArray)(params).map((item) => this.processItemOnIn(item, opt));
563
- }
564
- async afterSet(items, opt) {
565
- return items.map((item) => this.processItemOnOut(item, opt));
566
- }
567
- async beforeRemove(params, opt) {
568
- return this.defaultAfterAndBefore(params, opt);
569
- }
570
- async afterRemove(items, opt) {
571
- return items.map((item) => this.processItemOnOut(item, opt));
572
- }
573
- async beforeRemoveMany(params, opt) {
574
- return this.defaultAfterAndBefore(params, opt);
575
- }
576
- async afterRemoveMany(items, opt) {
577
- return items.map((item) => this.processItemOnOut(item, opt));
578
- }
579
- async onException(params, opt) {
580
- return '';
581
- }
582
- /**
583
- * Returns JWT secret and its settings to verify received JWT token
584
- * @param params Object of parameters passed to the authenticate method
585
- * @returns Object with the jwtSecret and verifyTokenArgs
586
- */
587
- async getJwtTokenSecretAndSettings(params) {
588
- const { space } = this.getContext();
589
- return {
590
- jwtSecret: space?.tokenSecret || this.config.jwtSecret || '',
591
- verifyTokenArgs: this.config.verifyTokenArgs,
592
- };
593
- }
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'];
603
- }
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'];
608
- }
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] || req.headers?.[constants_1.HEADERS.AUTHORIZATION] || authorization;
616
- const fingerprint = req.cookies?.[space.fingerprintCookieName] || req.headers?.[constants_1.HEADERS.FINGERPRINT] || args.fingerprint || '';
617
- return {
618
- token,
619
- fingerprint,
620
- };
621
- }
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)(),
645
- fingerprint,
646
- });
647
- if (verifyResult.didFail()) {
648
- return [false, verifyResult.getErrorSummary('')];
649
- }
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, ''];
662
- }
663
- else if (space?.apiKey && space?.apiKey !== context.apiKey) {
664
- return [false, 'API Key is invalid'];
665
- }
666
- }
667
- return [true, ''];
668
- }
669
- processRemovedRecord(record) {
670
- if (record && typeof record.id === 'string') {
671
- record.id = record.id.split('~')[0];
672
- }
673
- return record;
674
- }
675
- addRemovedModifierToFields(fields) {
676
- const obj = {};
677
- if (!fields) {
678
- this.logger.log(`The 'addRemovedModifierToFields' method expected its fields parameter to be a field name or an array of table field names but got:`, fields);
679
- return obj;
680
- }
681
- (0, lodash_1.castArray)(fields).forEach((field) => {
682
- obj[field] = this.getDb().raw(`${field} || '~removed~' || uuid_generate_v4()`);
683
- });
684
- return obj;
685
- }
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
- filter,
700
- params: {
701
- pagination: { pageSize: 1 },
702
- sortBy: [{ name: constants_1.FIELDS.ORDER_NO, order: constants_1.ORDER_BYS.DESC }],
703
- },
704
- });
705
- if (lastRecord.length > 0) {
706
- if (this.config.orderNoAsDecimal === true) {
707
- params.orderNo =
708
- lastRecord[0]?.orderNo != null
709
- ? Number(lastRecord[0]?.orderNo) + Number(constants_1.DEFAULT_ORDER_NO_STEP)
710
- : Number(constants_1.DEFAULT_ORDER_NO);
711
- }
712
- else {
713
- const order = new utils_1.StrOrderHelpers({
714
- start: lastRecord[0]?.orderNo || constants_1.DEFAULT_ORDER_NO,
715
- step: constants_1.DEFAULT_ORDER_NO_STEP,
716
- });
717
- params.orderNo = order.increase();
718
- }
719
- }
720
- }
721
- }
722
- }
723
- exports.BaseCore = BaseCore;