@sdflc/backend-helpers 1.0.106 → 1.0.107

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