@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,734 @@
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, roles, 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
+ // Check if the action requires simple role verification.
207
+ // If roles are provided but user has no role or user's roles is not included in the allowed roles then return an error
208
+ if (Array.isArray(roles) && roles?.length) {
209
+ const userRoleId = this.getContext().roleId || '';
210
+ if (!userRoleId) {
211
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FORBIDDEN, [], 'User has not assigned role');
212
+ }
213
+ else if (!roles.includes(userRoleId)) {
214
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FORBIDDEN, [], 'User role does not allow this operation');
215
+ }
216
+ }
217
+ let validatedItems = {};
218
+ if (typeof validate === 'function') {
219
+ this.measureTool.addCheckpoint('Validate parameters: start');
220
+ // If we have validator provided, use it to validate data before running action
221
+ // validator is expected to return an array:
222
+ // [0] - true or validation error object,
223
+ // [1] - an object with some fetched data to pass ot the action handler
224
+ const valideResult = await validate(args, actionOpt);
225
+ let result = valideResult;
226
+ if (Array.isArray(valideResult)) {
227
+ result = valideResult[0];
228
+ validatedItems = valideResult[1] || {};
229
+ }
230
+ // If validator returned null then consider the validation passed
231
+ result = result != null ? result : true;
232
+ this.measureTool.addCheckpoint('Validate parameters: end');
233
+ if (result !== true) {
234
+ // if there was an error then `result` is expected to be an object with the same structure as the checkit library does
235
+ await this.checkResult({ hasTransaction, result, sameRequest });
236
+ return result.code != null ? result : new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED });
237
+ }
238
+ }
239
+ let time = this.measureTool.stop();
240
+ this.logger.debug(`Authorization and validation time for the ${doingWhat} took ${time.durationMs} ms`);
241
+ const result = await action(args, { ...actionOpt, validatedItems, args });
242
+ await this.checkResult({ hasTransaction, result, sameRequest, doingWhat });
243
+ time = this.measureTool.stop(doingWhat);
244
+ this.logger.debug(`The ${time.name} process time is ${time.durationMs} ms`);
245
+ return result;
246
+ }
247
+ catch (ex) {
248
+ this.logger.error(`An exception has occurred on ${step}:`, ex);
249
+ if (!sameRequest && hasTransaction) {
250
+ this.logger.debug(`Rolling back DB transaction on ${step} due to an excaption`);
251
+ await this.getDb().rollbackTransaction();
252
+ }
253
+ let errMessage = '';
254
+ try {
255
+ errMessage = await this.onException(args, { ...actionOpt, doingWhat, exception: ex });
256
+ if (check_types_1.default.function(onException)) {
257
+ errMessage = await onException(args, { ...actionOpt, doingWhat, exception: ex });
258
+ }
259
+ }
260
+ catch (ex2) {
261
+ this.logger.error(`An exception has occured when handling exception:`, ex2);
262
+ }
263
+ if (!errMessage) {
264
+ errMessage = doingWhat;
265
+ }
266
+ if (doingWhat !== step) {
267
+ errMessage = `${step} failed on ${doingWhat}`;
268
+ }
269
+ const time = this.measureTool.stop(doingWhat);
270
+ this.logger.debug(`The ${time.name} process time is ${time.durationMs} ms`);
271
+ return this.exceptionFailure(ex, errMessage);
272
+ }
273
+ }
274
+ async list(args) {
275
+ return this.runAction({
276
+ args,
277
+ doAuth: this.config.doAuthOnAction?.list,
278
+ actionName: constants_1.ACTIONS.LIST,
279
+ validate: this.getValidators().list,
280
+ accessRights: [utils_1.ACCESS_RIGHTS.LIST],
281
+ action: async (args, opt) => {
282
+ const object = await this.beforeList(args, opt);
283
+ if (object instanceof api_helpers_1.OpResult) {
284
+ return object;
285
+ }
286
+ const items = await this.getContext().gateways[this.config.gatewayName]?.list(object);
287
+ const result = await this.afterList(items, opt);
288
+ // ON NO DATA RETURN EMPTY CODE
289
+ return this.success(result);
290
+ },
291
+ hasTransaction: false,
292
+ doingWhat: this.config.doingWhat?.list ?? this.config.name ?? 'listing',
293
+ });
294
+ }
295
+ async get(args) {
296
+ return this.runAction({
297
+ args,
298
+ doAuth: this.config.doAuthOnAction?.get,
299
+ actionName: constants_1.ACTIONS.GET,
300
+ validate: this.getValidators().get,
301
+ accessRights: [utils_1.ACCESS_RIGHTS.GET],
302
+ action: async (args, opt) => {
303
+ const args2use = await this.beforeGet(args, opt);
304
+ if (args2use instanceof api_helpers_1.OpResult) {
305
+ return args2use;
306
+ }
307
+ if (args2use?.id == null) {
308
+ return this.failure(api_helpers_1.OP_RESULT_CODES.NOT_FOUND, '', []);
309
+ }
310
+ const item = await this.getContext().gateways[this.config.gatewayName]?.get(args2use?.id);
311
+ const result = await this.afterGet(item, opt);
312
+ if (!result) {
313
+ return this.failure(api_helpers_1.OP_RESULT_CODES.NOT_FOUND, '', []);
314
+ }
315
+ return this.success([result]);
316
+ },
317
+ hasTransaction: false,
318
+ doingWhat: this.config.doingWhat?.get ?? this.config.name ?? 'getting an item',
319
+ });
320
+ }
321
+ async getMany(args) {
322
+ return this.runAction({
323
+ args,
324
+ doAuth: this.config.doAuthOnAction?.getMany,
325
+ actionName: constants_1.ACTIONS.GET_MANY,
326
+ validate: this.getValidators().getMany,
327
+ accessRights: [utils_1.ACCESS_RIGHTS.GET],
328
+ action: async (args, opt) => {
329
+ const args2use = await this.beforeGetMany(args, opt);
330
+ if (args2use instanceof api_helpers_1.OpResult) {
331
+ return args2use;
332
+ }
333
+ if (!Array.isArray(args2use?.ids)) {
334
+ return this.failure(api_helpers_1.OP_RESULT_CODES.NOT_FOUND, '', []);
335
+ }
336
+ const items = await this.getContext().gateways[this.config.gatewayName]?.getMany(args2use.ids);
337
+ const result = await this.afterGetMany(items, opt);
338
+ return this.success(result);
339
+ },
340
+ hasTransaction: false,
341
+ doingWhat: this.config.doingWhat?.getMany ?? this.config.name ?? 'geting multiple items',
342
+ });
343
+ }
344
+ getGatewayToSetOrerNo() {
345
+ return this.getContext().gateways[this.config.gatewayName];
346
+ }
347
+ getFilterToSetOrderNo(args) {
348
+ return {};
349
+ }
350
+ async create(args) {
351
+ return this.runAction({
352
+ args,
353
+ doAuth: this.config.doAuthOnAction?.create,
354
+ actionName: constants_1.ACTIONS.CREATE,
355
+ validate: this.getValidators().create,
356
+ accessRights: [utils_1.ACCESS_RIGHTS.CREATE],
357
+ action: async (args, opt) => {
358
+ const { params } = args || {};
359
+ if (this.config.hasOrderNo === true) {
360
+ await this.setOrderNo({
361
+ params,
362
+ filter: this.getFilterToSetOrderNo({ params, opt }),
363
+ gateway: this.getGatewayToSetOrerNo(),
364
+ });
365
+ }
366
+ const object = await this.beforeCreate(params, opt);
367
+ if (object instanceof api_helpers_1.OpResult) {
368
+ return object;
369
+ }
370
+ const items = await this.getContext().gateways[this.config.gatewayName]?.create(object);
371
+ const result = await this.afterCreate(items, opt);
372
+ return this.success(result);
373
+ },
374
+ hasTransaction: true,
375
+ doingWhat: this.config.doingWhat?.create ?? this.config.name ?? 'creating an item',
376
+ });
377
+ }
378
+ async createMany(args) {
379
+ return this.runAction({
380
+ args,
381
+ doAuth: this.config.doAuthOnAction?.createMany,
382
+ actionName: constants_1.ACTIONS.CREATE_MANY,
383
+ validate: this.getValidators().createMany,
384
+ accessRights: [utils_1.ACCESS_RIGHTS.CREATE],
385
+ action: async (args, opt) => {
386
+ const { params } = args || {};
387
+ const objects = await this.beforeCreateMany(params, opt);
388
+ if (objects instanceof api_helpers_1.OpResult) {
389
+ return objects;
390
+ }
391
+ const items = await this.getContext().gateways[this.config.gatewayName]?.create(objects);
392
+ const result = await this.afterCreateMany(items, opt);
393
+ return this.success(result);
394
+ },
395
+ hasTransaction: true,
396
+ doingWhat: this.config.doingWhat?.createMany ?? this.config.name ?? 'creating multiple items',
397
+ });
398
+ }
399
+ async update(args) {
400
+ return this.runAction({
401
+ args,
402
+ doAuth: this.config.doAuthOnAction?.update,
403
+ actionName: constants_1.ACTIONS.UPDATE,
404
+ validate: this.getValidators().update,
405
+ accessRights: [utils_1.ACCESS_RIGHTS.UPDATE],
406
+ action: async (args, opt) => {
407
+ const { where, params } = args || {};
408
+ const object = await this.beforeUpdate(params, opt);
409
+ if (object instanceof api_helpers_1.OpResult) {
410
+ return object;
411
+ }
412
+ const items = await this.getContext().gateways[this.config.gatewayName]?.update(where, object);
413
+ const result = await this.afterUpdate(items, opt);
414
+ return this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND);
415
+ },
416
+ hasTransaction: true,
417
+ doingWhat: this.config.doingWhat?.update ?? this.config.name ?? 'updating an item',
418
+ });
419
+ }
420
+ async updateMany(args) {
421
+ return this.runAction({
422
+ args,
423
+ doAuth: this.config.doAuthOnAction?.updateMany,
424
+ actionName: constants_1.ACTIONS.UPDATE_MANY,
425
+ validate: this.getValidators().updateMany,
426
+ accessRights: [utils_1.ACCESS_RIGHTS.UPDATE],
427
+ action: async (args, opt) => {
428
+ const { params } = args || {};
429
+ const object = await this.beforeUpdateMany(params, opt);
430
+ if (object instanceof api_helpers_1.OpResult) {
431
+ return object;
432
+ }
433
+ const items = await this.getContext().gateways[this.config.gatewayName]?.updateMany(object);
434
+ const result = await this.afterUpdateMany(items, opt);
435
+ return this.success(result);
436
+ },
437
+ hasTransaction: true,
438
+ doingWhat: this.config.doingWhat?.updateMany ?? this.config.name ?? 'updating multiple items',
439
+ });
440
+ }
441
+ async set(args) {
442
+ return this.runAction({
443
+ args,
444
+ doAuth: this.config.doAuthOnAction?.set,
445
+ actionName: constants_1.ACTIONS.SET,
446
+ validate: this.getValidators().set,
447
+ accessRights: [utils_1.ACCESS_RIGHTS.CREATE, utils_1.ACCESS_RIGHTS.UPDATE],
448
+ action: async (args, opt /* { setStep, validatedItems, sameRequest } */) => {
449
+ const { params } = args || {};
450
+ const object = await this.beforeSet(params, opt);
451
+ if (object instanceof api_helpers_1.OpResult) {
452
+ return object;
453
+ }
454
+ const items = await this.getContext().gateways[this.config.gatewayName]?.set(object);
455
+ const result = await this.afterSet(items, opt);
456
+ return this.success(result);
457
+ },
458
+ hasTransaction: true,
459
+ doingWhat: this.config.doingWhat?.updateMany ?? this.config.name ?? 'updating multiple items',
460
+ });
461
+ }
462
+ async remove(args) {
463
+ return this.runAction({
464
+ args,
465
+ doAuth: this.config.doAuthOnAction?.remove,
466
+ actionName: constants_1.ACTIONS.REMOVE,
467
+ validate: this.getValidators().remove,
468
+ accessRights: [utils_1.ACCESS_RIGHTS.REMOVE],
469
+ action: async (args, opt) => {
470
+ const { where } = args || {};
471
+ const object = await this.beforeRemove(where, opt);
472
+ if (object instanceof api_helpers_1.OpResult) {
473
+ return object;
474
+ }
475
+ const items = await this.getContext().gateways[this.config.gatewayName]?.remove(object);
476
+ const result = await this.afterRemove(items, opt);
477
+ return this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND);
478
+ },
479
+ hasTransaction: false,
480
+ doingWhat: this.config.doingWhat?.remove ?? this.config.name ?? 'removing an item',
481
+ });
482
+ }
483
+ async removeMany(args) {
484
+ return this.runAction({
485
+ args,
486
+ doAuth: this.config.doAuthOnAction?.removeMany,
487
+ actionName: constants_1.ACTIONS.REMOVE_MANY,
488
+ validate: this.getValidators().removeMany,
489
+ accessRights: [utils_1.ACCESS_RIGHTS.REMOVE],
490
+ action: async (args, opt) => {
491
+ const { where } = args || {};
492
+ const object = await this.beforeRemoveMany(where, opt);
493
+ if (object instanceof api_helpers_1.OpResult) {
494
+ return object;
495
+ }
496
+ const items = await this.getContext().gateways[this.config.gatewayName]?.remove(object);
497
+ const result = await this.afterRemoveMany(items, opt);
498
+ return this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND);
499
+ },
500
+ hasTransaction: false,
501
+ doingWhat: this.config.doingWhat?.removeMany ?? this.config.name ?? 'removing multiple items',
502
+ });
503
+ }
504
+ async defaultAfterAndBefore(params, opt) {
505
+ return params;
506
+ }
507
+ /**
508
+ * Used to transform an object before sending it in the response
509
+ * @param {any} item An object coming from the database
510
+ * @param {BaseCoreActionsInterface} opt Options
511
+ * @returns {any} transformed object
512
+ */
513
+ processItemOnOut(item, opt) {
514
+ return this.defaultAfterAndBefore(item, opt);
515
+ }
516
+ /**
517
+ * Used to transform an object before processing it on the request
518
+ * @param {any} item An object coming from the outside
519
+ * @param {BaseCoreActionsInterface} opt Options
520
+ * @returns {any} transformed object
521
+ */
522
+ processItemOnIn(item, opt) {
523
+ return this.defaultAfterAndBefore(item, opt);
524
+ }
525
+ async beforeGet(item, opt) {
526
+ return this.defaultAfterAndBefore(item, opt);
527
+ }
528
+ async beforeGetMany(items, opt) {
529
+ return this.defaultAfterAndBefore(items, opt);
530
+ }
531
+ async beforeList(filter, opt) {
532
+ return this.defaultAfterAndBefore(filter, opt);
533
+ }
534
+ async afterGet(item, opt) {
535
+ return this.processItemOnOut(item, opt);
536
+ }
537
+ async afterGetMany(items, opt) {
538
+ return items.map((item) => this.processItemOnOut(item, opt));
539
+ }
540
+ async afterList(items, opt) {
541
+ return items.map((item) => this.processItemOnOut(item, opt));
542
+ }
543
+ async beforeCreate(params, opt) {
544
+ return this.processItemOnIn(params, opt);
545
+ }
546
+ async afterCreate(items, opt) {
547
+ return items.map((item) => this.processItemOnOut(item, opt));
548
+ }
549
+ async beforeCreateMany(items, opt) {
550
+ return items.map((item) => this.processItemOnIn(item, opt));
551
+ }
552
+ async afterCreateMany(items, opt) {
553
+ return items.map((item) => this.processItemOnOut(item, opt));
554
+ }
555
+ async beforeUpdate(params, opt) {
556
+ return this.processItemOnIn(params, opt);
557
+ }
558
+ async afterUpdate(items, opt) {
559
+ return items.map((item) => this.processItemOnOut(item, opt));
560
+ }
561
+ async beforeUpdateMany(items, opt) {
562
+ return items.map((item) => {
563
+ return {
564
+ params: this.processItemOnIn(item.params, opt),
565
+ where: item.where,
566
+ };
567
+ });
568
+ }
569
+ async afterUpdateMany(items, opt) {
570
+ return items.map((item) => this.processItemOnOut(item, opt));
571
+ }
572
+ async beforeSet(params, opt) {
573
+ return (0, lodash_1.castArray)(params).map((item) => this.processItemOnIn(item, opt));
574
+ }
575
+ async afterSet(items, opt) {
576
+ return items.map((item) => this.processItemOnOut(item, opt));
577
+ }
578
+ async beforeRemove(params, opt) {
579
+ return this.defaultAfterAndBefore(params, opt);
580
+ }
581
+ async afterRemove(items, opt) {
582
+ return items.map((item) => this.processItemOnOut(item, opt));
583
+ }
584
+ async beforeRemoveMany(params, opt) {
585
+ return this.defaultAfterAndBefore(params, opt);
586
+ }
587
+ async afterRemoveMany(items, opt) {
588
+ return items.map((item) => this.processItemOnOut(item, opt));
589
+ }
590
+ async onException(params, opt) {
591
+ return '';
592
+ }
593
+ /**
594
+ * Returns JWT secret and its settings to verify received JWT token
595
+ * @param params Object of parameters passed to the authenticate method
596
+ * @returns Object with the jwtSecret and verifyTokenArgs
597
+ */
598
+ async getJwtTokenSecretAndSettings(params) {
599
+ const { space } = this.getContext();
600
+ return {
601
+ jwtSecret: space?.tokenSecret || this.config.jwtSecret || '',
602
+ verifyTokenArgs: this.config.verifyTokenArgs,
603
+ };
604
+ }
605
+ async findSpace() {
606
+ const { context } = this.config;
607
+ if (context.space) {
608
+ return [true, context.space];
609
+ }
610
+ let space = null;
611
+ if (context.spaceGw) {
612
+ if (!context.spaceId) {
613
+ return [false, 'Space not specified'];
614
+ }
615
+ // Lookup space in case we have gateway
616
+ space = await context.spaceGw.get(context.spaceId || '');
617
+ if (!space) {
618
+ return [false, 'Space not found'];
619
+ }
620
+ context.space = space;
621
+ }
622
+ return [true, space];
623
+ }
624
+ async extractCredentials(args) {
625
+ const { req, space, authorization } = args;
626
+ const token = req.cookies?.[space.cookieName] || req.headers?.[constants_1.HEADERS.AUTHORIZATION] || authorization;
627
+ const fingerprint = req.cookies?.[space.fingerprintCookieName] || req.headers?.[constants_1.HEADERS.FINGERPRINT] || args.fingerprint || '';
628
+ return {
629
+ token,
630
+ fingerprint,
631
+ };
632
+ }
633
+ async authenticate(params, opt) {
634
+ //const { accessRights } = params || {};
635
+ const context = this.getContext();
636
+ const { req, authorization } = context;
637
+ let authByToken = false;
638
+ const [spaceResult, space] = await this.findSpace();
639
+ if (spaceResult !== true) {
640
+ return [spaceResult, space];
641
+ }
642
+ const { token, fingerprint } = await this.extractCredentials({
643
+ req,
644
+ authorization,
645
+ fingerprint: context.fingerprint,
646
+ space,
647
+ params,
648
+ });
649
+ const { jwtSecret, verifyTokenArgs } = await this.getJwtTokenSecretAndSettings(params);
650
+ if (token && jwtSecret) {
651
+ const verifyResult = (0, userToken_1.verifyUserToken)(token, jwtSecret, {
652
+ ...verifyTokenArgs,
653
+ algorithms: verifyTokenArgs?.algorithms || [(0, userToken_1.getDefaultJwtAlgorithm)()],
654
+ audience: verifyTokenArgs?.audience || space.id,
655
+ issuer: verifyTokenArgs?.issuer || (0, userToken_1.getDefaultJwtIssuer)(),
656
+ fingerprint,
657
+ });
658
+ if (verifyResult.didFail()) {
659
+ return [false, verifyResult.getErrorSummary('')];
660
+ }
661
+ const tokenData = verifyResult.getDataFirst();
662
+ context.accountId = tokenData.accountId;
663
+ context.roleId = tokenData.roleId;
664
+ context.userId = tokenData.userId;
665
+ context.isSuperAdmin = context.roleId === 'superadmin';
666
+ context.spaceId = context.spaceId || tokenData.spaceId;
667
+ context.lang = context.requestedLang || tokenData.lang;
668
+ authByToken = true;
669
+ }
670
+ if (!authByToken) {
671
+ if (this.config.interserviceApiKey && context.apiKey === this.config.interserviceApiKey) {
672
+ return [true, ''];
673
+ }
674
+ else if (space?.apiKey && space?.apiKey !== context.apiKey) {
675
+ return [false, 'API Key is invalid'];
676
+ }
677
+ }
678
+ return [true, ''];
679
+ }
680
+ processRemovedRecord(record) {
681
+ if (record && typeof record.id === 'string') {
682
+ record.id = record.id.split('~')[0];
683
+ }
684
+ return record;
685
+ }
686
+ addRemovedModifierToFields(fields) {
687
+ const obj = {};
688
+ if (!fields) {
689
+ 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);
690
+ return obj;
691
+ }
692
+ (0, lodash_1.castArray)(fields).forEach((field) => {
693
+ obj[field] = this.getDb().raw(`${field} || '~removed~' || uuid_generate_v4()`);
694
+ });
695
+ return obj;
696
+ }
697
+ async setOrderNo(args) {
698
+ const { params, filter, gateway } = args || {};
699
+ if (typeof params !== 'object') {
700
+ throw new Error(`The 'setOrderNo' expected the parameter to have 'params' object but got: ${JSON.stringify(params)} `);
701
+ }
702
+ if (typeof gateway !== 'object') {
703
+ throw new Error(`The 'setOrderNo' expected the parameter to have 'gateway' object but got: ${JSON.stringify(gateway)} `);
704
+ }
705
+ if (typeof gateway.list !== 'function') {
706
+ throw new Error(`The 'setOrderNo' expected the 'gateway' object to have 'list' method but got: ${JSON.stringify(gateway.list)} `);
707
+ }
708
+ if (!params.orderNo) {
709
+ const lastRecord = await gateway.list({
710
+ filter,
711
+ params: {
712
+ pagination: { pageSize: 1 },
713
+ sortBy: [{ name: constants_1.FIELDS.ORDER_NO, order: constants_1.ORDER_BYS.DESC }],
714
+ },
715
+ });
716
+ if (lastRecord.length > 0) {
717
+ if (this.config.orderNoAsDecimal === true) {
718
+ params.orderNo =
719
+ lastRecord[0]?.orderNo != null
720
+ ? Number(lastRecord[0]?.orderNo) + Number(constants_1.DEFAULT_ORDER_NO_STEP)
721
+ : Number(constants_1.DEFAULT_ORDER_NO);
722
+ }
723
+ else {
724
+ const order = new utils_1.StrOrderHelpers({
725
+ start: lastRecord[0]?.orderNo || constants_1.DEFAULT_ORDER_NO,
726
+ step: constants_1.DEFAULT_ORDER_NO_STEP,
727
+ });
728
+ params.orderNo = order.increase();
729
+ }
730
+ }
731
+ }
732
+ }
733
+ }
734
+ exports.BaseCore = BaseCore;