@sdflc/backend-helpers 1.0.111 → 1.0.113

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 (206) hide show
  1. package/README.md +1422 -146
  2. package/build/BaseController.d.ts +20 -0
  3. package/build/BaseController.js +64 -0
  4. package/build/BaseCore.d.ts +470 -33
  5. package/build/BaseCore.js +613 -126
  6. package/build/BaseExternalApiGateway.d.ts +16 -0
  7. package/build/BaseExternalApiGateway.js +54 -0
  8. package/build/BaseGateway.d.ts +455 -17
  9. package/build/BaseGateway.js +502 -56
  10. package/build/BaseRestApiCrudController.d.ts +37 -0
  11. package/build/BaseRestApiCrudController.js +134 -0
  12. package/build/DataCache.d.ts +116 -5
  13. package/build/DataCache.js +144 -22
  14. package/build/Database.d.ts +165 -4
  15. package/build/Database.js +224 -51
  16. package/build/DbMigratorAndSeeder.d.ts +127 -26
  17. package/build/DbMigratorAndSeeder.js +180 -69
  18. package/build/RedisDataLoader.d.ts +144 -21
  19. package/build/RedisDataLoader.js +178 -49
  20. package/build/apiContext.d.ts +0 -8
  21. package/build/apiContext.js +12 -27
  22. package/build/checkItHelpers.d.ts +32 -0
  23. package/build/checkItHelpers.js +73 -7
  24. package/build/commonValidators.d.ts +107 -16
  25. package/build/commonValidators.js +211 -106
  26. package/build/configBuilder.d.ts +23 -0
  27. package/build/configBuilder.js +73 -0
  28. package/build/constants.d.ts +134 -17
  29. package/build/constants.js +95 -15
  30. package/build/dbHelpers.d.ts +89 -29
  31. package/build/dbHelpers.js +175 -86
  32. package/build/dbSeeder.d.ts +10 -1
  33. package/build/dbSeeder.js +80 -15
  34. package/build/dbTableHelpers.d.ts +122 -5
  35. package/build/dbTableHelpers.js +151 -13
  36. package/build/downloadHelpers.d.ts +24 -1
  37. package/build/downloadHelpers.js +51 -21
  38. package/build/esm/BaseController.d.ts +20 -0
  39. package/build/esm/BaseController.js +58 -0
  40. package/build/esm/BaseCore.d.ts +470 -33
  41. package/build/esm/BaseCore.js +615 -128
  42. package/build/esm/BaseExternalApiGateway.d.ts +16 -0
  43. package/build/esm/BaseExternalApiGateway.js +48 -0
  44. package/build/esm/BaseGateway.d.ts +455 -17
  45. package/build/esm/BaseGateway.js +503 -57
  46. package/build/esm/BaseRestApiCrudController.d.ts +37 -0
  47. package/build/esm/BaseRestApiCrudController.js +131 -0
  48. package/build/esm/DataCache.d.ts +116 -5
  49. package/build/esm/DataCache.js +142 -20
  50. package/build/esm/Database.d.ts +165 -4
  51. package/build/esm/Database.js +224 -51
  52. package/build/esm/DbMigratorAndSeeder.d.ts +127 -26
  53. package/build/esm/DbMigratorAndSeeder.js +184 -71
  54. package/build/esm/RedisDataLoader.d.ts +144 -21
  55. package/build/esm/RedisDataLoader.js +179 -50
  56. package/build/esm/apiContext.d.ts +0 -8
  57. package/build/esm/apiContext.js +12 -27
  58. package/build/esm/checkItHelpers.d.ts +32 -0
  59. package/build/esm/checkItHelpers.js +73 -7
  60. package/build/esm/commonValidators.d.ts +107 -16
  61. package/build/esm/commonValidators.js +209 -105
  62. package/build/esm/configBuilder.d.ts +23 -0
  63. package/build/esm/configBuilder.js +69 -0
  64. package/build/esm/constants.d.ts +134 -17
  65. package/build/esm/constants.js +94 -14
  66. package/build/esm/dbHelpers.d.ts +89 -29
  67. package/build/esm/dbHelpers.js +171 -81
  68. package/build/esm/dbSeeder.d.ts +10 -1
  69. package/build/esm/dbSeeder.js +81 -16
  70. package/build/esm/dbTableHelpers.d.ts +122 -5
  71. package/build/esm/dbTableHelpers.js +152 -14
  72. package/build/esm/downloadHelpers.d.ts +24 -1
  73. package/build/esm/downloadHelpers.js +51 -21
  74. package/build/esm/index.d.ts +5 -2
  75. package/build/esm/index.js +5 -2
  76. package/build/esm/interfaces/ApiContext.d.ts +7 -3
  77. package/build/esm/interfaces/ApiContextInterface.d.ts +1 -1
  78. package/build/esm/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  79. package/build/esm/interfaces/BaseControllerPropsInterface.js +1 -0
  80. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  81. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  82. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +87 -9
  83. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  84. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  85. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.js +2 -0
  86. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  87. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  88. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  89. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.js +2 -0
  90. package/build/esm/interfaces/BuildConfigOptions.d.ts +18 -0
  91. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  92. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  93. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  94. package/build/esm/interfaces/CacheInterface.d.ts +18 -1
  95. package/build/esm/interfaces/CacheInterface.js +1 -0
  96. package/build/esm/interfaces/CoreActionInterface.d.ts +20 -0
  97. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +38 -4
  98. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  99. package/build/esm/interfaces/DataCachePropsInterface.d.ts +21 -0
  100. package/build/esm/interfaces/DataCachePropsInterface.js +2 -0
  101. package/build/esm/interfaces/DatabaseOptions.d.ts +24 -10
  102. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  103. package/build/esm/interfaces/DatabaseReadInterface.d.ts +58 -3
  104. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  105. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  106. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  107. package/build/esm/interfaces/DownloadFileArgs.d.ts +21 -2
  108. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  109. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  110. package/build/esm/interfaces/ListArgsInterface.d.ts +18 -0
  111. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  112. package/build/esm/interfaces/LoaderInterface.d.ts +36 -1
  113. package/build/esm/interfaces/LoaderInterface.js +1 -0
  114. package/build/esm/interfaces/UserTokenParams.d.ts +23 -5
  115. package/build/esm/interfaces/UserTokenParams.js +1 -0
  116. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  117. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  118. package/build/esm/interfaces/index.d.ts +4 -0
  119. package/build/esm/interfaces/index.js +4 -0
  120. package/build/esm/knexConfigBuilder.d.ts +25 -0
  121. package/build/esm/knexConfigBuilder.js +100 -36
  122. package/build/esm/parseIds.d.ts +6 -0
  123. package/build/esm/parseIds.js +13 -0
  124. package/build/esm/passwordHelpers.d.ts +22 -0
  125. package/build/esm/passwordHelpers.js +40 -8
  126. package/build/esm/redisClient.d.ts +57 -4
  127. package/build/esm/redisClient.js +40 -54
  128. package/build/esm/resolveClientIp.d.ts +15 -0
  129. package/build/esm/resolveClientIp.js +34 -0
  130. package/build/esm/resolversHelpers.d.ts +21 -1
  131. package/build/esm/resolversHelpers.js +48 -26
  132. package/build/esm/userToken.d.ts +50 -1
  133. package/build/esm/userToken.js +85 -20
  134. package/build/esm/utils.d.ts +20 -0
  135. package/build/esm/utils.js +23 -1
  136. package/build/index.d.ts +5 -2
  137. package/build/index.js +5 -2
  138. package/build/interfaces/ApiContext.d.ts +7 -3
  139. package/build/interfaces/ApiContextInterface.d.ts +1 -1
  140. package/build/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  141. package/build/interfaces/BaseControllerPropsInterface.js +2 -0
  142. package/build/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  143. package/build/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  144. package/build/interfaces/BaseCorePropsInterface.d.ts +87 -9
  145. package/build/interfaces/BaseCorePropsInterface.js +1 -0
  146. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  147. package/build/interfaces/BaseExternalApiGatewayPropsInterface.js +3 -0
  148. package/build/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  149. package/build/interfaces/BaseGatewayPropsInterface.js +1 -0
  150. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  151. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.js +3 -0
  152. package/build/interfaces/BuildConfigOptions.d.ts +18 -0
  153. package/build/interfaces/BuildConfigOptions.js +1 -0
  154. package/build/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  155. package/build/interfaces/BuildListQueryArgsInterface.js +1 -0
  156. package/build/interfaces/CacheInterface.d.ts +18 -1
  157. package/build/interfaces/CacheInterface.js +1 -0
  158. package/build/interfaces/CoreActionInterface.d.ts +20 -0
  159. package/build/interfaces/CreateUserTokenArgs.d.ts +38 -4
  160. package/build/interfaces/CreateUserTokenArgs.js +1 -0
  161. package/build/interfaces/DataCachePropsInterface.d.ts +21 -0
  162. package/build/interfaces/DataCachePropsInterface.js +3 -0
  163. package/build/interfaces/DatabaseOptions.d.ts +24 -10
  164. package/build/interfaces/DatabaseOptions.js +1 -0
  165. package/build/interfaces/DatabaseReadInterface.d.ts +58 -3
  166. package/build/interfaces/DatabaseReadInterface.js +1 -0
  167. package/build/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  168. package/build/interfaces/DbFieldAddDefaultInterface.js +1 -0
  169. package/build/interfaces/DownloadFileArgs.d.ts +21 -2
  170. package/build/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  171. package/build/interfaces/ExtractCredentialsArgs.js +1 -0
  172. package/build/interfaces/ListArgsInterface.d.ts +18 -0
  173. package/build/interfaces/ListArgsInterface.js +1 -0
  174. package/build/interfaces/LoaderInterface.d.ts +36 -1
  175. package/build/interfaces/LoaderInterface.js +1 -0
  176. package/build/interfaces/UserTokenParams.d.ts +23 -5
  177. package/build/interfaces/UserTokenParams.js +1 -0
  178. package/build/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  179. package/build/interfaces/VerifyUserTokenArgs.js +1 -0
  180. package/build/interfaces/index.d.ts +4 -0
  181. package/build/interfaces/index.js +4 -0
  182. package/build/knexConfigBuilder.d.ts +25 -0
  183. package/build/knexConfigBuilder.js +99 -35
  184. package/build/parseIds.d.ts +6 -0
  185. package/build/parseIds.js +17 -0
  186. package/build/passwordHelpers.d.ts +22 -0
  187. package/build/passwordHelpers.js +40 -8
  188. package/build/redisClient.d.ts +57 -4
  189. package/build/redisClient.js +40 -54
  190. package/build/resolveClientIp.d.ts +15 -0
  191. package/build/resolveClientIp.js +38 -0
  192. package/build/resolversHelpers.d.ts +21 -1
  193. package/build/resolversHelpers.js +48 -26
  194. package/build/userToken.d.ts +50 -1
  195. package/build/userToken.js +85 -20
  196. package/build/utils.d.ts +20 -0
  197. package/build/utils.js +23 -1
  198. package/package.json +19 -18
  199. package/build/baseController.d.ts +0 -17
  200. package/build/baseController.js +0 -63
  201. package/build/configBulder.d.ts +0 -2
  202. package/build/configBulder.js +0 -36
  203. package/build/esm/baseController.d.ts +0 -17
  204. package/build/esm/baseController.js +0 -57
  205. package/build/esm/configBulder.d.ts +0 -2
  206. package/build/esm/configBulder.js +0 -32
@@ -1,79 +1,175 @@
1
- import { OpResult, OP_RESULT_CODES } from '@sdflc/api-helpers';
2
- import { Logger, ACCESS_RIGHTS, MeasureTool, StrOrderHelpers, LoggerLevels } from '@sdflc/utils';
1
+ // ./src/BaseCore.ts
2
+ import { OpResult, OP_RESULT_CODES, isOpResult } from '@sdflc/api-helpers';
3
+ import { Logger, ACCESS_RIGHTS, MeasureTool, StrOrderHelpers, LoggerLevels, isLogger } from '@sdflc/utils';
3
4
  import check from 'check-types';
4
5
  import { castArray } from 'lodash';
5
6
  import { validateGet, validateGetMany, validateRemove, validateRemoveMany } from './commonValidators';
6
7
  import { ACTIONS, DEFAULT_ORDER_NO, DEFAULT_ORDER_NO_STEP, FIELDS, HEADERS, ID_TYPES, ORDER_BYS } from './constants';
7
8
  import { getDefaultJwtAlgorithm, getDefaultJwtIssuer, verifyUserToken } from './userToken';
8
- const defaultValidate = ( /*args: any, opt?: BaseCoreActionsInterface*/) => {
9
+ /**
10
+ * Default no-op validator — allows all operations through without checks.
11
+ * Used as the fallback for action types that do not define custom validation.
12
+ */
13
+ const defaultValidate = () => {
9
14
  return [true, {}];
10
15
  };
11
- const defaultMutationValidate = ( /*args: any, opt?: BaseCoreActionsInterface*/) => {
16
+ /**
17
+ * Default no-op validator for mutation operations (create, update, set).
18
+ * Kept separate from defaultValidate so subclasses can override mutation
19
+ * validation independently of read validation if needed.
20
+ */
21
+ const defaultMutationValidate = () => {
12
22
  return [true, {}];
13
23
  };
24
+ /**
25
+ * Default validator map applied to all actions unless overridden via `getValidators()`.
26
+ * Read operations (get, getMany) use stricter built-in validators that check
27
+ * for required id fields. Mutations use the permissive no-op default.
28
+ */
14
29
  const defaultValidators = {
15
30
  list: defaultValidate,
16
31
  get: validateGet,
17
32
  getMany: validateGetMany,
18
- create: defaultValidate,
19
- createMany: defaultValidate,
20
- update: defaultValidate,
21
- updateMany: defaultValidate,
22
- set: defaultValidate,
33
+ create: defaultMutationValidate,
34
+ createMany: defaultMutationValidate,
35
+ update: defaultMutationValidate,
36
+ updateMany: defaultMutationValidate,
37
+ set: defaultMutationValidate,
23
38
  remove: validateRemove,
24
39
  removeMany: validateRemoveMany,
25
40
  };
41
+ /**
42
+ * Module-level logger used as the initial fallback before the instance logger
43
+ * is resolved from config. Set to ERROR level to suppress noise during construction.
44
+ */
45
+ const localLogger = new Logger({ level: LoggerLevels.ERROR });
46
+ /**
47
+ * BaseCore is the foundation for all business-logic core classes.
48
+ *
49
+ * A core sits between the transport layer (GraphQL resolvers, REST controllers)
50
+ * and the data layer (gateways). It is responsible for:
51
+ * - Authentication and authorisation (via `runAction`)
52
+ * - Input validation (via validator functions)
53
+ * - Database transaction management
54
+ * - Calling gateway methods and transforming results
55
+ * - Consistent error handling and OpResult wrapping
56
+ *
57
+ * Cores are instantiated per-request and receive a full `BaseCorePropsInterface`
58
+ * including the ApiContext, db, logger, auth config, etc.
59
+ *
60
+ * Subclasses typically override:
61
+ * - `getValidators()` — to provide custom validation per action
62
+ * - `before*` / `after*` — to transform inputs/outputs per action
63
+ * - `processItemOnIn()` — to normalise inbound data
64
+ * - `processItemOnOut()` — to shape outbound data
65
+ * - `authenticate()` — to implement custom auth strategies
66
+ * - `getJwtTokenSecretAndSettings()` — to resolve JWT config per space/tenant
67
+ * - `onException()` — to customise exception messages
68
+ * - `getFilterToSetOrderNo()` — to scope orderNo sequences to a parent entity
69
+ */
26
70
  class BaseCore {
27
71
  measureTool = new MeasureTool();
28
72
  config;
29
73
  logger;
30
74
  constructor(props) {
31
75
  this.config = props || {};
32
- this.logger = this.config.logger instanceof Logger ? this.config.logger : new Logger({ level: LoggerLevels.ERROR });
76
+ // Start with the module-level fallback logger, then upgrade to the
77
+ // configured one if it passes the duck-type check.
78
+ // Duck-type check avoids instanceof failures across package versions.
79
+ this.logger = localLogger;
80
+ if (this.config.logger && isLogger(this.config.logger)) {
81
+ this.logger = this.config.logger;
82
+ }
83
+ // Resolve per-action auth flags. Each action can independently enable or
84
+ // disable auth via doAuthOnAction. If not explicitly set for an action,
85
+ // it falls back to the top-level doAuth flag. This allows a core to
86
+ // require auth globally while exempting specific actions (e.g. list).
33
87
  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,
88
+ list: props?.doAuthOnAction?.list != null ? props.doAuthOnAction.list : props?.doAuth,
89
+ get: props?.doAuthOnAction?.get != null ? props.doAuthOnAction.get : props?.doAuth,
90
+ getMany: props?.doAuthOnAction?.getMany != null ? props.doAuthOnAction.getMany : props?.doAuth,
91
+ create: props?.doAuthOnAction?.create != null ? props.doAuthOnAction.create : props?.doAuth,
92
+ createMany: props?.doAuthOnAction?.createMany != null ? props.doAuthOnAction.createMany : props?.doAuth,
93
+ update: props?.doAuthOnAction?.update != null ? props.doAuthOnAction.update : props?.doAuth,
94
+ updateMany: props?.doAuthOnAction?.updateMany != null ? props.doAuthOnAction.updateMany : props?.doAuth,
95
+ set: props?.doAuthOnAction?.set != null ? props.doAuthOnAction.set : props?.doAuth,
96
+ remove: props?.doAuthOnAction?.remove != null ? props.doAuthOnAction.remove : props?.doAuth,
97
+ removeMany: props?.doAuthOnAction?.removeMany != null ? props.doAuthOnAction.removeMany : props?.doAuth,
44
98
  };
45
99
  }
100
+ /**
101
+ * Returns the ID type this core operates with (UUID, integer, etc.).
102
+ * Defaults to ID_TYPES.UNKNOWN if not configured.
103
+ * Used by consumers that need to validate or coerce ID formats.
104
+ */
46
105
  getIdType() {
47
106
  return this.config.idType ?? ID_TYPES.UNKNOWN;
48
107
  }
108
+ /**
109
+ * Returns the Database instance from config.
110
+ * Used for transaction management and raw query access.
111
+ */
49
112
  getDb() {
50
113
  return this.config.db;
51
114
  }
115
+ /**
116
+ * Returns the requestId from the current ApiContext.
117
+ * Used to detect same-request calls (see `sameRequest` logic in runAction).
118
+ */
52
119
  getRequestId() {
53
120
  return this.config.context.requestId;
54
121
  }
122
+ /**
123
+ * Returns the full ApiContext for this request.
124
+ * Contains userId, spaceId, gateways, cores, headers, etc.
125
+ */
55
126
  getContext() {
56
127
  return this.config.context;
57
128
  }
129
+ /**
130
+ * Returns all gateway instances from the current request context.
131
+ * Returns an empty object if context or gateways are not available.
132
+ */
58
133
  getGateways() {
59
- return this.config.context.gateways || {};
134
+ return this.config.context?.gateways || {};
60
135
  }
136
+ /**
137
+ * Returns a single gateway by name.
138
+ * Falls back to `config.gatewayName` if no name is provided.
139
+ * Returns undefined if the gateway does not exist in context.
140
+ */
61
141
  getGateway(name) {
62
- return this.getGateways()?.[name || this.config.gatewayName];
142
+ const gwName = name || this.config.gatewayName;
143
+ return gwName && this.getGateways()?.[gwName];
63
144
  }
145
+ /**
146
+ * Returns the validator map for this core.
147
+ * Override in subclasses to provide custom validators per action.
148
+ *
149
+ * Each validator is a function (or async function) that receives
150
+ * `(args, actionOpt)` and returns `[result, validatedItems]` where:
151
+ * - result === true means validation passed
152
+ * - result is a validation error object if validation failed
153
+ * - validatedItems is an optional object of pre-fetched/validated data
154
+ * that will be merged into actionOpt for the action handler
155
+ */
64
156
  getValidators() {
65
157
  return defaultValidators;
66
158
  }
159
+ /**
160
+ * Wraps data in a successful OpResult and returns its plain JS representation.
161
+ *
162
+ * Always returns data as an array — single objects are wrapped in `[data]`.
163
+ * Empty/null data returns an empty array with OK status.
164
+ *
165
+ * @param data The data to include in the result
166
+ * @param code Optional result code (defaults to OP_RESULT_CODES.OK)
167
+ */
67
168
  success(data, code) {
68
169
  const code2use = code != null ? code : OP_RESULT_CODES.OK;
69
170
  let data2use = data;
70
171
  if (!Array.isArray(data2use)) {
71
- if (data) {
72
- data2use = [data];
73
- }
74
- else {
75
- data2use = [];
76
- }
172
+ data2use = data ? [data] : [];
77
173
  }
78
174
  return new OpResult({
79
175
  code: code2use,
@@ -81,20 +177,36 @@ class BaseCore {
81
177
  errors: [],
82
178
  }).toJS();
83
179
  }
180
+ /**
181
+ * Creates a failed OpResult with a single error message.
182
+ *
183
+ * @param code Result code (e.g. OP_RESULT_CODES.NOT_FOUND)
184
+ * @param errorMsg Human-readable error description
185
+ * @param data Optional data payload to include alongside the error
186
+ */
84
187
  failure(code, errorMsg, data) {
85
188
  const result = new OpResult({ data });
86
189
  result.addError('', errorMsg, code);
87
190
  return result.toJS();
88
191
  }
192
+ /**
193
+ * Creates a validation-failed OpResult from a validation error object.
194
+ *
195
+ * Handles two cases:
196
+ * - If `ex` is already an OpResult, returns a plain VALIDATION_FAILED result
197
+ * (the original OpResult's errors are not re-wrapped to avoid duplication)
198
+ * - Otherwise, iterates `ex.errors` (checkit library format) and adds each
199
+ * field's error messages individually, supporting both single and multiple
200
+ * rule failures per field
201
+ */
89
202
  validationFailure(ex) {
90
203
  const result = new OpResult({ code: OP_RESULT_CODES.VALIDATION_FAILED });
91
- if (ex instanceof OpResult) {
204
+ if (isOpResult(ex)) {
92
205
  return result.toJS();
93
206
  }
94
207
  Object.keys(ex?.errors || {}).forEach((key) => {
95
208
  const obj = ex.errors[key];
96
209
  if (Array.isArray(obj.errors)) {
97
- // if we have multiple rules failures the add them all
98
210
  obj.errors.forEach((item) => {
99
211
  result.addError(key, item.message);
100
212
  });
@@ -105,23 +217,51 @@ class BaseCore {
105
217
  });
106
218
  return result.toJS();
107
219
  }
220
+ /**
221
+ * Creates an exception-failed OpResult from a caught error.
222
+ *
223
+ * Distinguishes between database errors (returned to the client with the
224
+ * DB-level message) and application errors (logged internally, generic
225
+ * message returned to the client to avoid leaking implementation details).
226
+ *
227
+ * Note: uses `isExOpResult` instead of `isOpResult` to avoid shadowing
228
+ * the imported `isOpResult` utility function.
229
+ *
230
+ * @param ex The caught exception
231
+ * @param doingWhat Description of the operation that failed (for logging)
232
+ * @param data Optional data payload to include in the result
233
+ */
108
234
  exceptionFailure(ex, doingWhat, data) {
109
235
  const [isDbError, dbErrorMsg] = this.getDb().isDbError(ex);
110
- const isOpResult = typeof ex.getErrorSummary === 'function';
111
- const message = isOpResult ? ex.getErrorSummary() : ex.message;
236
+ // Renamed from `isOpResult` to avoid shadowing the imported utility
237
+ const isExOpResult = typeof ex.getErrorSummary === 'function';
238
+ const message = isExOpResult ? ex.getErrorSummary() : ex.message;
112
239
  const sysMsg = `An exception has occurred on ${doingWhat} with message ${message}:`;
113
- let msg = '';
240
+ let msg;
114
241
  if (isDbError) {
242
+ // DB errors are safe to surface — they come from the DB driver, not app logic
115
243
  msg = dbErrorMsg;
116
244
  }
117
245
  else {
118
- msg = isOpResult ? ex.getErrorSummary() : `Sorry, something went wrong on ${doingWhat}`;
246
+ // Non-DB errors: log the full detail internally, return a safe generic message
247
+ msg = isExOpResult ? ex.getErrorSummary() : `Sorry, something went wrong on ${doingWhat}`;
119
248
  this.logger.error(sysMsg, ex);
120
249
  }
121
250
  const result = new OpResult({ data });
122
251
  result.addError('', msg, OP_RESULT_CODES.EXCEPTION);
123
252
  return result.toJS();
124
253
  }
254
+ /**
255
+ * Commits or rolls back the active database transaction based on the action result.
256
+ *
257
+ * Called at the end of every `runAction()` flow, including in the catch block.
258
+ * Does nothing if `hasTransaction` is false or if `sameRequest` is true
259
+ * (same-request calls share their caller's transaction).
260
+ *
261
+ * `skipCheckResult` forces a commit regardless of result code — useful for
262
+ * operations where the caller has already verified correctness and just needs
263
+ * the transaction closed (e.g. after a manual rollback-and-retry pattern).
264
+ */
125
265
  async checkResult(args) {
126
266
  const { hasTransaction, result, sameRequest, doingWhat, skipCheckResult } = args;
127
267
  if (sameRequest) {
@@ -149,15 +289,38 @@ class BaseCore {
149
289
  }
150
290
  }
151
291
  }
292
+ /**
293
+ * Core action runner. All public CRUD methods delegate to this.
294
+ *
295
+ * Execution flow:
296
+ * 1. Detect same-request calls (skip transaction + auth for nested calls
297
+ * within the same request, identified by matching requestId)
298
+ * 2. Start DB transaction if `hasTransaction` is true
299
+ * 3. Authenticate the request (if `doAuth` is true) OR verify the space
300
+ * (if `requireSpace` is not false) — space verification is a lighter
301
+ * alternative to full auth for public-but-space-scoped operations
302
+ * 4. Check role-based access if `roles` array is provided
303
+ * 5. Run the validator function if provided — validator returns
304
+ * `[true, validatedItems]` on success or `[errorObj, {}]` on failure
305
+ * 6. Execute the action handler with `(args, { ...actionOpt, validatedItems })`
306
+ * 7. Commit or rollback the transaction via `checkResult()`
307
+ * 8. On any exception: rollback, call `onException()` and the caller's
308
+ * `onException` hook, then return an exceptionFailure result
309
+ *
310
+ * Same-request detection:
311
+ * When a core method calls another core method on the same request
312
+ * (e.g. create calling list to re-fetch results), it can pass
313
+ * `args.requestId = context.requestId`. The inner call detects this,
314
+ * skips starting a new transaction, skips auth, and skips committing —
315
+ * the outer call owns the transaction lifecycle.
316
+ *
317
+ * @param opt CoreActionInterface with all action configuration
318
+ */
152
319
  async runAction(opt) {
153
- const { args, validate, doAuth, roles, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace, skipCheckResult, } = opt || {};
154
- // If we process action with the same requestId as requestId passed to the constructor it means
155
- // we are processing the same request from FE and can skip some of the operations like transactions and etc
320
+ const { args, validate, doAuth, tryAuth, roles, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace, skipCheckResult, } = opt || {};
321
+ // Detect if this is a nested call within the same request.
322
+ // If so, skip transaction management and auth to avoid double-wrapping.
156
323
  const sameRequest = !!this.config.context.requestId && args?.requestId === this.config.context.requestId;
157
- // TODO: Calculate total thread block time between async calls withing the request
158
- // this.measureTool.threadBlockTime(doingWhat, ({ name, durationMs }: any) => {
159
- // this.logger.debug(`The ${name} blocked thread for the time of ${durationMs} ms`);
160
- // });
161
324
  if (shouldLogArgs == null || shouldLogArgs === true) {
162
325
  this.logger.debug(`The ${doingWhat} started:`, args);
163
326
  }
@@ -166,6 +329,8 @@ class BaseCore {
166
329
  }
167
330
  this.measureTool.start();
168
331
  let step = doingWhat || '';
332
+ // setStep is passed to action handlers and validators so they can emit
333
+ // granular timing checkpoints that appear in debug logs.
169
334
  const setStep = (stepName) => {
170
335
  step = stepName || step;
171
336
  const time = this.measureTool.addCheckpoint(stepName);
@@ -196,7 +361,21 @@ class BaseCore {
196
361
  return result;
197
362
  }
198
363
  }
364
+ else if (tryAuth === true) {
365
+ // Soft auth — attempt to populate context from token but never fail.
366
+ // Errors are swallowed intentionally — the request continues either way.
367
+ this.measureTool.addCheckpoint('Try authenticate request: start');
368
+ try {
369
+ await this.authenticate(opt, actionOpt);
370
+ }
371
+ catch (ex) {
372
+ this.logger.debug(`The ${step} soft authentication attempt failed silently:`, ex);
373
+ }
374
+ this.measureTool.addCheckpoint('Try authenticate request: end');
375
+ }
199
376
  else if (requireSpace == null || requireSpace === true) {
377
+ // Space verification: lighter than full auth — confirms the request
378
+ // is targeting a known, valid space without verifying user identity.
200
379
  this.measureTool.addCheckpoint('Find space: start');
201
380
  const [spaceResult, errMsg] = await this.findSpace();
202
381
  this.measureTool.addCheckpoint('Find space: end');
@@ -208,9 +387,9 @@ class BaseCore {
208
387
  }
209
388
  }
210
389
  }
211
- // Check if the action requires simple role verification.
212
- // If roles are provided but user has no role or user's roles is not included in the allowed roles then return an error
213
- if (Array.isArray(roles) && roles?.length) {
390
+ // Role check: simpler than full RBAC — verifies the user's roleId is in
391
+ // the allowed list for this action. Checked after auth so roleId is populated.
392
+ if (Array.isArray(roles) && roles.length > 0) {
214
393
  const userRoleId = this.getContext().roleId || '';
215
394
  if (!userRoleId) {
216
395
  return OpResult.fail(OP_RESULT_CODES.FORBIDDEN, [], 'User has not assigned role');
@@ -222,21 +401,22 @@ class BaseCore {
222
401
  let validatedItems = {};
223
402
  if (typeof validate === 'function') {
224
403
  this.measureTool.addCheckpoint('Validate parameters: start');
225
- // If we have validator provided, use it to validate data before running action
226
- // validator is expected to return an array:
227
- // [0] - true or validation error object,
228
- // [1] - an object with some fetched data to pass ot the action handler
404
+ // Validator returns [result, validatedItems]:
405
+ // - result === true: validation passed
406
+ // - result === null: treated as passed (some validators return null on success)
407
+ // - result is object: validation failed, object contains error details
408
+ // validatedItems carries any data the validator pre-fetched
409
+ // (e.g. the existing record for an update) so the action handler
410
+ // doesn't need to re-fetch it.
229
411
  const valideResult = await validate(args, actionOpt);
230
412
  let result = valideResult;
231
413
  if (Array.isArray(valideResult)) {
232
414
  result = valideResult[0];
233
415
  validatedItems = valideResult[1] || {};
234
416
  }
235
- // If validator returned null then consider the validation passed
236
417
  result = result != null ? result : true;
237
418
  this.measureTool.addCheckpoint('Validate parameters: end');
238
419
  if (result !== true) {
239
- // if there was an error then `result` is expected to be an object with the same structure as the checkit library does
240
420
  await this.checkResult({ hasTransaction, result, sameRequest });
241
421
  return result.code != null ? result : new OpResult({ code: OP_RESULT_CODES.VALIDATION_FAILED });
242
422
  }
@@ -252,10 +432,12 @@ class BaseCore {
252
432
  catch (ex) {
253
433
  this.logger.error(`An exception has occurred on ${step}:`, ex);
254
434
  if (!sameRequest && hasTransaction) {
255
- this.logger.debug(`Rolling back DB transaction on ${step} due to an excaption`);
435
+ this.logger.debug(`Rolling back DB transaction on ${step} due to an exception`);
256
436
  await this.getDb().rollbackTransaction();
257
437
  }
258
- let errMessage = '';
438
+ // Initialise to doingWhat so context is preserved even if the
439
+ // exception handler itself throws.
440
+ let errMessage;
259
441
  try {
260
442
  errMessage = await this.onException(args, { ...actionOpt, doingWhat, exception: ex });
261
443
  if (check.function(onException)) {
@@ -263,7 +445,10 @@ class BaseCore {
263
445
  }
264
446
  }
265
447
  catch (ex2) {
266
- this.logger.error(`An exception has occured when handling exception:`, ex2);
448
+ // If the exception handler itself throws, fall back to doingWhat
449
+ // so the outer exceptionFailure still has meaningful context.
450
+ this.logger.error(`An exception has occurred when handling exception:`, ex2);
451
+ errMessage = doingWhat;
267
452
  }
268
453
  if (!errMessage) {
269
454
  errMessage = doingWhat;
@@ -276,6 +461,13 @@ class BaseCore {
276
461
  return this.exceptionFailure(ex, errMessage);
277
462
  }
278
463
  }
464
+ /**
465
+ * Lists records via the configured gateway.
466
+ *
467
+ * Calls `beforeList()` to transform filter args, then `afterList()` on results.
468
+ * Auth is controlled by `doAuthOnAction.list`.
469
+ * Does not use a DB transaction — list is a read-only operation.
470
+ */
279
471
  async list(args) {
280
472
  return this.runAction({
281
473
  args,
@@ -285,18 +477,27 @@ class BaseCore {
285
477
  accessRights: [ACCESS_RIGHTS.LIST],
286
478
  action: async (args, opt) => {
287
479
  const object = await this.beforeList(args, opt);
288
- if (object instanceof OpResult) {
480
+ if (isOpResult(object)) {
289
481
  return object;
290
482
  }
291
- const items = await this.getContext().gateways[this.config.gatewayName]?.list(object);
483
+ const items = await this.getGateway()?.list(object);
292
484
  const result = await this.afterList(items, opt);
293
- // ON NO DATA RETURN EMPTY CODE
294
485
  return this.success(result);
295
486
  },
296
487
  hasTransaction: false,
297
488
  doingWhat: this.config.doingWhat?.list ?? this.config.name ?? 'listing',
298
489
  });
299
490
  }
491
+ /**
492
+ * Fetches a single record by id via the configured gateway.
493
+ *
494
+ * Calls `beforeGet()` to transform/validate the args object (which should
495
+ * contain an `id` field). Returns NOT_FOUND if:
496
+ * - beforeGet returns null/undefined id
497
+ * - the gateway returns no record for that id
498
+ *
499
+ * Does not use a DB transaction.
500
+ */
300
501
  async get(args) {
301
502
  return this.runAction({
302
503
  args,
@@ -306,13 +507,13 @@ class BaseCore {
306
507
  accessRights: [ACCESS_RIGHTS.GET],
307
508
  action: async (args, opt) => {
308
509
  const args2use = await this.beforeGet(args, opt);
309
- if (args2use instanceof OpResult) {
510
+ if (isOpResult(args2use)) {
310
511
  return args2use;
311
512
  }
312
513
  if (args2use?.id == null) {
313
514
  return this.failure(OP_RESULT_CODES.NOT_FOUND, '', []);
314
515
  }
315
- const item = await this.getContext().gateways[this.config.gatewayName]?.get(args2use?.id);
516
+ const item = await this.getGateway()?.get(args2use.id);
316
517
  const result = await this.afterGet(item, opt);
317
518
  if (!result) {
318
519
  return this.failure(OP_RESULT_CODES.NOT_FOUND, '', []);
@@ -323,6 +524,16 @@ class BaseCore {
323
524
  doingWhat: this.config.doingWhat?.get ?? this.config.name ?? 'getting an item',
324
525
  });
325
526
  }
527
+ /**
528
+ * Fetches multiple records by their ids via the configured gateway.
529
+ *
530
+ * Calls `beforeGetMany()` to transform the args object (which should
531
+ * contain an `ids` array). Returns NOT_FOUND if `ids` is not an array
532
+ * after the before-hook.
533
+ *
534
+ * Results are returned in DataLoader order (same order as input ids,
535
+ * with null entries for missing records). Does not use a DB transaction.
536
+ */
326
537
  async getMany(args) {
327
538
  return this.runAction({
328
539
  args,
@@ -332,26 +543,41 @@ class BaseCore {
332
543
  accessRights: [ACCESS_RIGHTS.GET],
333
544
  action: async (args, opt) => {
334
545
  const args2use = await this.beforeGetMany(args, opt);
335
- if (args2use instanceof OpResult) {
546
+ if (isOpResult(args2use)) {
336
547
  return args2use;
337
548
  }
338
549
  if (!Array.isArray(args2use?.ids)) {
339
- return this.failure(OP_RESULT_CODES.NOT_FOUND, '', []);
550
+ return this.failure(OP_RESULT_CODES.NOT_FOUND, 'Expected ids array but received invalid input', []);
340
551
  }
341
- const items = await this.getContext().gateways[this.config.gatewayName]?.getMany(args2use.ids);
552
+ const items = await this.getGateway()?.getMany(args2use.ids);
342
553
  const result = await this.afterGetMany(items, opt);
343
554
  return this.success(result);
344
555
  },
345
556
  hasTransaction: false,
346
- doingWhat: this.config.doingWhat?.getMany ?? this.config.name ?? 'geting multiple items',
557
+ doingWhat: this.config.doingWhat?.getMany ?? this.config.name ?? 'getting multiple items',
347
558
  });
348
559
  }
560
+ /**
561
+ * Returns the gateway instance used for orderNo calculation.
562
+ * Override in subclasses to use a different gateway than the default one.
563
+ */
349
564
  getGatewayToSetOrerNo() {
350
- return this.getContext().gateways[this.config.gatewayName];
565
+ return this.getGateway();
351
566
  }
352
- getFilterToSetOrderNo(args) {
567
+ /**
568
+ * Returns the filter object used when querying for the last orderNo value.
569
+ * Override in subclasses to scope orderNo sequences to a parent entity
570
+ * (e.g. return `{ categoryId: params.categoryId }` to have per-category ordering).
571
+ */
572
+ getFilterToSetOrderNo(_args) {
353
573
  return {};
354
574
  }
575
+ /**
576
+ * Creates a single record via the configured gateway.
577
+ *
578
+ * If `config.hasOrderNo` is true, auto-calculates the next orderNo value
579
+ * before calling `beforeCreate()`. Uses a DB transaction.
580
+ */
355
581
  async create(args) {
356
582
  return this.runAction({
357
583
  args,
@@ -369,10 +595,10 @@ class BaseCore {
369
595
  });
370
596
  }
371
597
  const object = await this.beforeCreate(params, opt);
372
- if (object instanceof OpResult) {
598
+ if (isOpResult(object)) {
373
599
  return object;
374
600
  }
375
- const items = await this.getContext().gateways[this.config.gatewayName]?.create(object);
601
+ const items = await this.getGateway()?.create(object);
376
602
  const result = await this.afterCreate(items, opt);
377
603
  return this.success(result);
378
604
  },
@@ -380,6 +606,13 @@ class BaseCore {
380
606
  doingWhat: this.config.doingWhat?.create ?? this.config.name ?? 'creating an item',
381
607
  });
382
608
  }
609
+ /**
610
+ * Creates multiple records in a single gateway call.
611
+ *
612
+ * Calls `beforeCreateMany()` which maps each item through `processItemOnIn()`
613
+ * using `Promise.all` to correctly resolve async transforms.
614
+ * Uses a DB transaction.
615
+ */
383
616
  async createMany(args) {
384
617
  return this.runAction({
385
618
  args,
@@ -390,10 +623,10 @@ class BaseCore {
390
623
  action: async (args, opt) => {
391
624
  const { params } = args || {};
392
625
  const objects = await this.beforeCreateMany(params, opt);
393
- if (objects instanceof OpResult) {
626
+ if (isOpResult(objects)) {
394
627
  return objects;
395
628
  }
396
- const items = await this.getContext().gateways[this.config.gatewayName]?.create(objects);
629
+ const items = await this.getGateway()?.create(objects);
397
630
  const result = await this.afterCreateMany(items, opt);
398
631
  return this.success(result);
399
632
  },
@@ -401,6 +634,16 @@ class BaseCore {
401
634
  doingWhat: this.config.doingWhat?.createMany ?? this.config.name ?? 'creating multiple items',
402
635
  });
403
636
  }
637
+ /**
638
+ * Updates a single record matching the `where` filter.
639
+ *
640
+ * `args` should contain `{ where, params }`:
641
+ * - `where` carries the filter (id, optional version for optimistic locking)
642
+ * - `params` carries the fields to update
643
+ *
644
+ * Returns NOT_FOUND if the gateway reports 0 affected records.
645
+ * Uses a DB transaction.
646
+ */
404
647
  async update(args) {
405
648
  return this.runAction({
406
649
  args,
@@ -411,10 +654,10 @@ class BaseCore {
411
654
  action: async (args, opt) => {
412
655
  const { where, params } = args || {};
413
656
  const object = await this.beforeUpdate(params, opt);
414
- if (object instanceof OpResult) {
657
+ if (isOpResult(object)) {
415
658
  return object;
416
659
  }
417
- const items = await this.getContext().gateways[this.config.gatewayName]?.update(where, object);
660
+ const items = await this.getGateway()?.update(where, object);
418
661
  const result = await this.afterUpdate(items, opt);
419
662
  return this.success(result, result.length > 0 ? OP_RESULT_CODES.OK : OP_RESULT_CODES.NOT_FOUND);
420
663
  },
@@ -422,6 +665,13 @@ class BaseCore {
422
665
  doingWhat: this.config.doingWhat?.update ?? this.config.name ?? 'updating an item',
423
666
  });
424
667
  }
668
+ /**
669
+ * Updates multiple records, each with its own where/params pair.
670
+ *
671
+ * `args.params` should be an array of `{ where, params }` objects.
672
+ * Each is processed sequentially by the gateway's `updateMany()`.
673
+ * Uses a DB transaction.
674
+ */
425
675
  async updateMany(args) {
426
676
  return this.runAction({
427
677
  args,
@@ -432,10 +682,10 @@ class BaseCore {
432
682
  action: async (args, opt) => {
433
683
  const { params } = args || {};
434
684
  const object = await this.beforeUpdateMany(params, opt);
435
- if (object instanceof OpResult) {
685
+ if (isOpResult(object)) {
436
686
  return object;
437
687
  }
438
- const items = await this.getContext().gateways[this.config.gatewayName]?.updateMany(object);
688
+ const items = await this.getGateway()?.updateMany(object);
439
689
  const result = await this.afterUpdateMany(items, opt);
440
690
  return this.success(result);
441
691
  },
@@ -443,6 +693,14 @@ class BaseCore {
443
693
  doingWhat: this.config.doingWhat?.updateMany ?? this.config.name ?? 'updating multiple items',
444
694
  });
445
695
  }
696
+ /**
697
+ * Upserts one or more records via the gateway's `set()` method
698
+ * (INSERT ... ON CONFLICT ... MERGE).
699
+ *
700
+ * `args.params` can be a single object or array. Each item is passed
701
+ * through `processItemOnIn()` via `beforeSet()`.
702
+ * Uses a DB transaction.
703
+ */
446
704
  async set(args) {
447
705
  return this.runAction({
448
706
  args,
@@ -450,20 +708,27 @@ class BaseCore {
450
708
  actionName: ACTIONS.SET,
451
709
  validate: this.getValidators().set,
452
710
  accessRights: [ACCESS_RIGHTS.CREATE, ACCESS_RIGHTS.UPDATE],
453
- action: async (args, opt /* { setStep, validatedItems, sameRequest } */) => {
711
+ action: async (args, opt) => {
454
712
  const { params } = args || {};
455
713
  const object = await this.beforeSet(params, opt);
456
- if (object instanceof OpResult) {
714
+ if (isOpResult(object)) {
457
715
  return object;
458
716
  }
459
- const items = await this.getContext().gateways[this.config.gatewayName]?.set(object);
717
+ const items = await this.getGateway()?.set(object);
460
718
  const result = await this.afterSet(items, opt);
461
719
  return this.success(result);
462
720
  },
463
721
  hasTransaction: true,
464
- doingWhat: this.config.doingWhat?.updateMany ?? this.config.name ?? 'updating multiple items',
722
+ doingWhat: this.config.doingWhat?.set ?? this.config.name ?? 'setting items',
465
723
  });
466
724
  }
725
+ /**
726
+ * Soft- or hard-deletes a single record matching `args.where`.
727
+ *
728
+ * The actual delete behaviour (hard vs soft) is determined by gateway config.
729
+ * Returns NOT_FOUND if the gateway reports 0 affected records.
730
+ * Does not use a DB transaction (remove is typically a single atomic operation).
731
+ */
467
732
  async remove(args) {
468
733
  return this.runAction({
469
734
  args,
@@ -474,10 +739,10 @@ class BaseCore {
474
739
  action: async (args, opt) => {
475
740
  const { where } = args || {};
476
741
  const object = await this.beforeRemove(where, opt);
477
- if (object instanceof OpResult) {
742
+ if (isOpResult(object)) {
478
743
  return object;
479
744
  }
480
- const items = await this.getContext().gateways[this.config.gatewayName]?.remove(object);
745
+ const items = await this.getGateway()?.remove(object);
481
746
  const result = await this.afterRemove(items, opt);
482
747
  return this.success(result, result.length > 0 ? OP_RESULT_CODES.OK : OP_RESULT_CODES.NOT_FOUND);
483
748
  },
@@ -485,6 +750,13 @@ class BaseCore {
485
750
  doingWhat: this.config.doingWhat?.remove ?? this.config.name ?? 'removing an item',
486
751
  });
487
752
  }
753
+ /**
754
+ * Removes multiple records matching `args.where`.
755
+ *
756
+ * Delegates to the gateway's `remove()` method (not `removeMany`) —
757
+ * the gateway's `onRemoveFilter` handles the multi-id WHERE clause.
758
+ * Does not use a DB transaction.
759
+ */
488
760
  async removeMany(args) {
489
761
  return this.runAction({
490
762
  args,
@@ -495,10 +767,10 @@ class BaseCore {
495
767
  action: async (args, opt) => {
496
768
  const { where } = args || {};
497
769
  const object = await this.beforeRemoveMany(where, opt);
498
- if (object instanceof OpResult) {
770
+ if (isOpResult(object)) {
499
771
  return object;
500
772
  }
501
- const items = await this.getContext().gateways[this.config.gatewayName]?.remove(object);
773
+ const items = await this.getGateway()?.remove(object);
502
774
  const result = await this.afterRemoveMany(items, opt);
503
775
  return this.success(result, result.length > 0 ? OP_RESULT_CODES.OK : OP_RESULT_CODES.NOT_FOUND);
504
776
  },
@@ -506,107 +778,238 @@ class BaseCore {
506
778
  doingWhat: this.config.doingWhat?.removeMany ?? this.config.name ?? 'removing multiple items',
507
779
  });
508
780
  }
509
- async defaultAfterAndBefore(params, opt) {
781
+ // ─── Before / After hooks ──────────────────────────────────────────────────
782
+ // These hooks are the primary extension points for subclasses.
783
+ // The before-* hooks transform input before it reaches the gateway.
784
+ // The after-* hooks transform output before it is returned to the caller.
785
+ // All hooks receive `opt: BaseCoreActionsInterface` which includes the core
786
+ // instance, setStep, and any validatedItems from the validator.
787
+ /**
788
+ * Default identity transform used by all before/after hooks that have
789
+ * no specific logic. Simply returns the params unchanged.
790
+ * Override to add cross-cutting transforms that apply to all actions.
791
+ */
792
+ async defaultAfterAndBefore(params, _opt) {
510
793
  return params;
511
794
  }
512
795
  /**
513
- * Used to transform an object before sending it in the response
514
- * @param {any} item An object coming from the database
515
- * @param {BaseCoreActionsInterface} opt Options
516
- * @returns {any} transformed object
796
+ * Transforms an outbound record (from DB to caller).
797
+ * Override to rename fields, attach computed properties, or strip sensitive data.
798
+ * Called by all after-* hooks via their Promise.all map loops.
517
799
  */
518
- processItemOnOut(item, opt) {
800
+ async processItemOnOut(item, opt) {
519
801
  return this.defaultAfterAndBefore(item, opt);
520
802
  }
521
803
  /**
522
- * Used to transform an object before processing it on the request
523
- * @param {any} item An object coming from the outside
524
- * @param {BaseCoreActionsInterface} opt Options
525
- * @returns {any} transformed object
804
+ * Transforms an inbound record (from caller to DB).
805
+ * Override to normalise fields, enforce defaults, or coerce types before writes.
806
+ * Called by all before-* mutation hooks via their Promise.all map loops.
526
807
  */
527
- processItemOnIn(item, opt) {
808
+ async processItemOnIn(item, opt) {
528
809
  return this.defaultAfterAndBefore(item, opt);
529
810
  }
811
+ /**
812
+ * Transforms the args object before a get() call.
813
+ * The returned object should contain an `id` field.
814
+ * If it returns an OpResult, `get()` will return that OpResult directly.
815
+ */
530
816
  async beforeGet(item, opt) {
531
817
  return this.defaultAfterAndBefore(item, opt);
532
818
  }
819
+ /**
820
+ * Transforms the args object before a getMany() call.
821
+ * The returned object should contain an `ids` array.
822
+ * If it returns an OpResult, `getMany()` will return that OpResult directly.
823
+ */
533
824
  async beforeGetMany(items, opt) {
534
825
  return this.defaultAfterAndBefore(items, opt);
535
826
  }
827
+ /**
828
+ * Transforms the filter/args object before a list() call.
829
+ * Override to inject default filters, enforce scope restrictions, etc.
830
+ * If it returns an OpResult, `list()` will return that OpResult directly.
831
+ */
536
832
  async beforeList(filter, opt) {
537
833
  return this.defaultAfterAndBefore(filter, opt);
538
834
  }
835
+ /**
836
+ * Transforms a single fetched record after get().
837
+ * Delegates to `processItemOnOut()`.
838
+ */
539
839
  async afterGet(item, opt) {
540
840
  return this.processItemOnOut(item, opt);
541
841
  }
842
+ /**
843
+ * Transforms fetched records after getMany().
844
+ * Maps each item through `processItemOnOut()` using Promise.all
845
+ * to correctly handle async transforms.
846
+ */
542
847
  async afterGetMany(items, opt) {
543
- return items.map((item) => this.processItemOnOut(item, opt));
848
+ return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
544
849
  }
850
+ /**
851
+ * Transforms fetched records after list().
852
+ * Maps each item through `processItemOnOut()` using Promise.all.
853
+ */
545
854
  async afterList(items, opt) {
546
- return items.map((item) => this.processItemOnOut(item, opt));
855
+ return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
547
856
  }
857
+ /**
858
+ * Transforms a single record before create().
859
+ * Delegates to `processItemOnIn()`.
860
+ */
548
861
  async beforeCreate(params, opt) {
549
862
  return this.processItemOnIn(params, opt);
550
863
  }
864
+ /**
865
+ * Transforms created records after create().
866
+ * Maps each item through `processItemOnOut()` using Promise.all.
867
+ */
551
868
  async afterCreate(items, opt) {
552
- return items.map((item) => this.processItemOnOut(item, opt));
869
+ return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
553
870
  }
871
+ /**
872
+ * Transforms an array of records before createMany().
873
+ * Maps each item through `processItemOnIn()` using Promise.all
874
+ * to correctly resolve async transforms.
875
+ *
876
+ * Fix: was using .map() without Promise.all, returning Promise[]
877
+ * instead of resolved values.
878
+ */
554
879
  async beforeCreateMany(items, opt) {
555
- return items.map((item) => this.processItemOnIn(item, opt));
880
+ return Promise.all(items.map((item) => this.processItemOnIn(item, opt)));
556
881
  }
882
+ /**
883
+ * Transforms created records after createMany().
884
+ * Maps each item through `processItemOnOut()` using Promise.all.
885
+ */
557
886
  async afterCreateMany(items, opt) {
558
- return items.map((item) => this.processItemOnOut(item, opt));
887
+ return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
559
888
  }
889
+ /**
890
+ * Transforms a single record before update().
891
+ * Delegates to `processItemOnIn()`.
892
+ */
560
893
  async beforeUpdate(params, opt) {
561
894
  return this.processItemOnIn(params, opt);
562
895
  }
896
+ /**
897
+ * Transforms updated records after update().
898
+ * Maps each item through `processItemOnOut()` using Promise.all.
899
+ */
563
900
  async afterUpdate(items, opt) {
564
- return items.map((item) => this.processItemOnOut(item, opt));
901
+ return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
565
902
  }
903
+ /**
904
+ * Transforms an array of { where, params } objects before updateMany().
905
+ * Maps each item's `params` through `processItemOnIn()` while preserving
906
+ * the `where` filter unchanged.
907
+ *
908
+ * Fix: was using .map() without Promise.all, returning Promise[]
909
+ * instead of resolved values.
910
+ */
566
911
  async beforeUpdateMany(items, opt) {
567
- return items.map((item) => {
568
- return {
569
- params: this.processItemOnIn(item.params, opt),
570
- where: item.where,
571
- };
572
- });
912
+ return Promise.all(items.map(async (item) => ({
913
+ params: await this.processItemOnIn(item.params, opt),
914
+ where: item.where,
915
+ })));
573
916
  }
917
+ /**
918
+ * Transforms updated records after updateMany().
919
+ * Maps each item through `processItemOnOut()` using Promise.all.
920
+ */
574
921
  async afterUpdateMany(items, opt) {
575
- return items.map((item) => this.processItemOnOut(item, opt));
922
+ return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
576
923
  }
924
+ /**
925
+ * Transforms params before set() (upsert).
926
+ * Normalises params to an array via castArray, then maps each item
927
+ * through `processItemOnIn()` using Promise.all.
928
+ *
929
+ * Fix: was using .map() without Promise.all, returning Promise[]
930
+ * instead of resolved values.
931
+ */
577
932
  async beforeSet(params, opt) {
578
- return castArray(params).map((item) => this.processItemOnIn(item, opt));
933
+ return Promise.all(castArray(params).map((item) => this.processItemOnIn(item, opt)));
579
934
  }
935
+ /**
936
+ * Transforms upserted records after set().
937
+ * Maps each item through `processItemOnOut()` using Promise.all.
938
+ */
580
939
  async afterSet(items, opt) {
581
- return items.map((item) => this.processItemOnOut(item, opt));
940
+ return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
582
941
  }
942
+ /**
943
+ * Transforms the where filter before remove().
944
+ * Override to add ownership checks or enrich the filter before deletion.
945
+ * If it returns an OpResult, `remove()` returns that OpResult directly.
946
+ */
583
947
  async beforeRemove(params, opt) {
584
948
  return this.defaultAfterAndBefore(params, opt);
585
949
  }
950
+ /**
951
+ * Transforms removed records after remove().
952
+ * Maps each item through `processItemOnOut()` using Promise.all.
953
+ */
586
954
  async afterRemove(items, opt) {
587
- return items.map((item) => this.processItemOnOut(item, opt));
955
+ return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
588
956
  }
957
+ /**
958
+ * Transforms the where filter before removeMany().
959
+ * Same contract as beforeRemove() but for bulk removal.
960
+ */
589
961
  async beforeRemoveMany(params, opt) {
590
962
  return this.defaultAfterAndBefore(params, opt);
591
963
  }
964
+ /**
965
+ * Transforms removed records after removeMany().
966
+ * Maps each item through `processItemOnOut()` using Promise.all.
967
+ */
592
968
  async afterRemoveMany(items, opt) {
593
- return items.map((item) => this.processItemOnOut(item, opt));
969
+ return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
594
970
  }
595
- async onException(params, opt) {
971
+ /**
972
+ * Called when `runAction()` catches an unhandled exception.
973
+ * Override to return a custom human-readable error message for specific
974
+ * exception types, or to trigger side effects (e.g. alert notifications).
975
+ *
976
+ * Return an empty string or null to let the default error handling apply.
977
+ * The caller's `onException` hook (passed to runAction) is called after this.
978
+ */
979
+ async onException(_params, _opt) {
596
980
  return '';
597
981
  }
598
982
  /**
599
- * Returns JWT secret and its settings to verify received JWT token
600
- * @param params Object of parameters passed to the authenticate method
601
- * @returns Object with the jwtSecret and verifyTokenArgs
983
+ * Returns the JWT secret and verification settings for the current request.
984
+ * Called by `authenticate()` to resolve auth config per space/tenant.
985
+ *
986
+ * Override to implement per-space token secrets, custom algorithms,
987
+ * or audience/issuer values derived from the request context.
988
+ *
989
+ * @param _params The args object passed to the action being authenticated
602
990
  */
603
- async getJwtTokenSecretAndSettings(params) {
991
+ async getJwtTokenSecretAndSettings(_params) {
604
992
  const { space } = this.getContext();
605
993
  return {
606
994
  jwtSecret: space?.tokenSecret || this.config.jwtSecret || '',
607
995
  verifyTokenArgs: this.config.verifyTokenArgs,
608
996
  };
609
997
  }
998
+ /**
999
+ * Resolves the current space from context or via the spaceGw gateway.
1000
+ *
1001
+ * Returns `[true, space]` on success, `[false, errorMessage]` on failure.
1002
+ *
1003
+ * Resolution order:
1004
+ * 1. If `context.space` is already populated, return it immediately
1005
+ * (avoids a redundant DB lookup on subsequent calls within the same request)
1006
+ * 2. If `spaceGw` is configured, look up the space by `context.spaceId`
1007
+ * 3. If no `spaceGw` is configured, return `[true, null]` —
1008
+ * callers must handle the null space case
1009
+ *
1010
+ * Side effect: on successful lookup, `context.space` is populated for
1011
+ * future calls within the same request.
1012
+ */
610
1013
  async findSpace() {
611
1014
  const { context } = this.config;
612
1015
  if (context.space) {
@@ -617,7 +1020,6 @@ class BaseCore {
617
1020
  if (!context.spaceId) {
618
1021
  return [false, 'Space not specified'];
619
1022
  }
620
- // Lookup space in case we have gateway
621
1023
  space = await context.spaceGw.get(context.spaceId || '');
622
1024
  if (!space) {
623
1025
  return [false, 'Space not found'];
@@ -626,17 +1028,55 @@ class BaseCore {
626
1028
  }
627
1029
  return [true, space];
628
1030
  }
1031
+ /**
1032
+ * Extracts the authentication token and fingerprint from the request.
1033
+ * Called by `authenticate()` before token verification.
1034
+ *
1035
+ * Token resolution order:
1036
+ * 1. Cookie named `space.cookieName`
1037
+ * 2. Authorization header
1038
+ * 3. `authorization` from context (passed explicitly, e.g. from API gateway)
1039
+ *
1040
+ * Fingerprint resolution order:
1041
+ * 1. Cookie named `space.fingerprintCookieName`
1042
+ * 2. X-Fingerprint header
1043
+ * 3. `args.fingerprint` passed to the function
1044
+ *
1045
+ * Override to support additional token sources (e.g. query string tokens
1046
+ * for WebSocket connections, or custom header schemes).
1047
+ */
629
1048
  async extractCredentials(args) {
630
1049
  const { req, space, authorization } = args;
631
1050
  const token = req.cookies?.[space.cookieName] || req.headers?.[HEADERS.AUTHORIZATION] || authorization;
632
1051
  const fingerprint = req.cookies?.[space.fingerprintCookieName] || req.headers?.[HEADERS.FINGERPRINT] || args.fingerprint || '';
633
- return {
634
- token,
635
- fingerprint,
636
- };
1052
+ return { token, fingerprint };
637
1053
  }
638
- async authenticate(params, opt) {
639
- //const { accessRights } = params || {};
1054
+ /**
1055
+ * Authenticates the current request.
1056
+ * Called by `runAction()` when `doAuth` is true.
1057
+ *
1058
+ * Returns `[true, '']` on success, `[false, errorMessage]` on failure.
1059
+ *
1060
+ * Authentication flow:
1061
+ * 1. Resolve the current space via `findSpace()`
1062
+ * 2. Extract token + fingerprint via `extractCredentials()`
1063
+ * 3. Resolve JWT secret via `getJwtTokenSecretAndSettings()`
1064
+ * 4. If a token and secret are present, verify the JWT:
1065
+ * - On success: populate context with accountId, roleId, userId,
1066
+ * isSuperAdmin, spaceId, lang from token payload
1067
+ * - On failure: return the verification error
1068
+ * 5. If no token was present, fall back to API key auth:
1069
+ * - Interservice API key (config.interserviceApiKey) for service-to-service calls
1070
+ * - Space API key (space.apiKey) for public API access
1071
+ * - If neither matches: return 'No authentication provided'
1072
+ *
1073
+ * Note: context.spaceId is only set from the token if not already present
1074
+ * in context (header value takes precedence). context.lang defaults to
1075
+ * empty string if neither requestedLang nor tokenData.lang is available.
1076
+ *
1077
+ * Override to add MFA checks, session validation, or custom token formats.
1078
+ */
1079
+ async authenticate(params, _opt) {
640
1080
  const context = this.getContext();
641
1081
  const { req, authorization } = context;
642
1082
  let authByToken = false;
@@ -668,30 +1108,55 @@ class BaseCore {
668
1108
  context.roleId = tokenData.roleId;
669
1109
  context.userId = tokenData.userId;
670
1110
  context.isSuperAdmin = context.roleId === 'superadmin';
671
- context.spaceId = context.spaceId || tokenData.spaceId;
672
- context.lang = context.requestedLang || tokenData.lang;
1111
+ // Header spaceId takes precedence over token spaceId
1112
+ context.spaceId = context.spaceId || tokenData.spaceId || '';
1113
+ // requestedLang (from Accept-Language header) takes precedence over token lang
1114
+ context.lang = context.requestedLang || tokenData.lang || '';
673
1115
  authByToken = true;
674
1116
  }
675
1117
  if (!authByToken) {
676
1118
  if (this.config.interserviceApiKey && context.apiKey === this.config.interserviceApiKey) {
1119
+ // Interservice call — trusted API key for service-to-service communication
677
1120
  return [true, ''];
678
1121
  }
679
1122
  else if (space?.apiKey && space?.apiKey !== context.apiKey) {
680
1123
  return [false, 'API Key is invalid'];
681
1124
  }
1125
+ return [false, 'No authentication provided'];
682
1126
  }
683
1127
  return [true, ''];
684
1128
  }
1129
+ /**
1130
+ * Strips the removal suffix from a soft-deleted record's id.
1131
+ *
1132
+ * When a record is soft-deleted with `hasLang`, the gateway appends
1133
+ * a timestamp to the id (e.g. "my-slug_en-20240101T120000+0000") to free
1134
+ * the original key for re-use. This method extracts the original id
1135
+ * by splitting at '~'.
1136
+ */
685
1137
  processRemovedRecord(record) {
686
1138
  if (record && typeof record.id === 'string') {
687
1139
  record.id = record.id.split('~')[0];
688
1140
  }
689
1141
  return record;
690
1142
  }
1143
+ /**
1144
+ * Builds a partial update object that appends a removal suffix to the
1145
+ * specified fields using a raw DB expression.
1146
+ *
1147
+ * Used to "tombstone" unique fields (slugs, emails, etc.) when soft-deleting,
1148
+ * freeing them for re-use on new records. The suffix includes a UUID to
1149
+ * ensure uniqueness even if the same record is deleted multiple times.
1150
+ *
1151
+ * Example: `{ slug: db.raw("slug || '~removed~' || uuid_generate_v4()") }`
1152
+ *
1153
+ * @param fields A single field name or array of field names to tombstone
1154
+ */
691
1155
  addRemovedModifierToFields(fields) {
692
1156
  const obj = {};
693
1157
  if (!fields) {
694
- this.logger.warn(`The 'addRemovedModifierToFields' method expected its fields parameter to be a field name or an array of table field names but got:`, fields);
1158
+ this.logger.warn(`The 'addRemovedModifierToFields' method expected its fields parameter to be a field name ` +
1159
+ `or an array of table field names but got:`, fields);
695
1160
  return obj;
696
1161
  }
697
1162
  castArray(fields).forEach((field) => {
@@ -699,18 +1164,40 @@ class BaseCore {
699
1164
  });
700
1165
  return obj;
701
1166
  }
1167
+ /**
1168
+ * Calculates and sets the next `orderNo` value on `params` before a create.
1169
+ * Called by `create()` when `config.hasOrderNo` is true.
1170
+ *
1171
+ * Queries the gateway for the last record (sorted by orderNo DESC, limit 1)
1172
+ * using the provided filter, then increments by `DEFAULT_ORDER_NO_STEP`.
1173
+ *
1174
+ * Supports two ordering strategies via `config.orderNoAsDecimal`:
1175
+ * - `true` — numeric ordering (e.g. 10, 20, 30)
1176
+ * - `false` — lexicographic string ordering via StrOrderHelpers
1177
+ * (e.g. "a", "b", "c" — useful for reordering without renumbering)
1178
+ *
1179
+ * Does nothing if `params.orderNo` is already set (non-null).
1180
+ *
1181
+ * Fix: changed `!params.orderNo` to `params.orderNo == null` to correctly
1182
+ * handle the case where `orderNo` is explicitly set to `0`.
1183
+ *
1184
+ * @param args.params The params object to mutate with the orderNo value
1185
+ * @param args.filter Filter to scope the orderNo sequence (e.g. by parentId)
1186
+ * @param args.gateway Gateway instance to query for the current max orderNo
1187
+ */
702
1188
  async setOrderNo(args) {
703
1189
  const { params, filter, gateway } = args || {};
704
1190
  if (typeof params !== 'object') {
705
- throw new Error(`The 'setOrderNo' expected the parameter to have 'params' object but got: ${JSON.stringify(params)} `);
1191
+ throw new Error(`The 'setOrderNo' expected the parameter to have 'params' object but got: ${JSON.stringify(params)}`);
706
1192
  }
707
1193
  if (typeof gateway !== 'object') {
708
- throw new Error(`The 'setOrderNo' expected the parameter to have 'gateway' object but got: ${JSON.stringify(gateway)} `);
1194
+ throw new Error(`The 'setOrderNo' expected the parameter to have 'gateway' object but got: ${JSON.stringify(gateway)}`);
709
1195
  }
710
1196
  if (typeof gateway.list !== 'function') {
711
- throw new Error(`The 'setOrderNo' expected the 'gateway' object to have 'list' method but got: ${JSON.stringify(gateway.list)} `);
1197
+ throw new Error(`The 'setOrderNo' expected the 'gateway' object to have 'list' method but got: ${JSON.stringify(gateway.list)}`);
712
1198
  }
713
- if (!params.orderNo) {
1199
+ // Fix: use == null instead of falsy check so orderNo: 0 is not overwritten
1200
+ if (params.orderNo == null) {
714
1201
  const lastRecord = await gateway.list({
715
1202
  filter,
716
1203
  params: {
@@ -722,7 +1209,7 @@ class BaseCore {
722
1209
  if (this.config.orderNoAsDecimal === true) {
723
1210
  params.orderNo =
724
1211
  lastRecord[0]?.orderNo != null
725
- ? Number(lastRecord[0]?.orderNo) + Number(DEFAULT_ORDER_NO_STEP)
1212
+ ? Number(lastRecord[0].orderNo) + Number(DEFAULT_ORDER_NO_STEP)
726
1213
  : Number(DEFAULT_ORDER_NO);
727
1214
  }
728
1215
  else {