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