@sdflc/backend-helpers 1.0.112 → 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 +608 -127
- 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 +599 -118
- 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 -2
- package/build/esm/utils.js +23 -13
- 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 -2
- package/build/utils.js +24 -16
- package/package.json +19 -18
- package/build/baseController.d.ts +0 -17
- package/build/baseController.js +0 -64
- 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 -58
- 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,80 +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
|
-
|
|
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 = () => {
|
|
16
20
|
return [true, {}];
|
|
17
21
|
};
|
|
18
|
-
|
|
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 = () => {
|
|
19
28
|
return [true, {}];
|
|
20
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
|
+
*/
|
|
21
35
|
const defaultValidators = {
|
|
22
36
|
list: defaultValidate,
|
|
23
37
|
get: commonValidators_1.validateGet,
|
|
24
38
|
getMany: commonValidators_1.validateGetMany,
|
|
25
|
-
create:
|
|
26
|
-
createMany:
|
|
27
|
-
update:
|
|
28
|
-
updateMany:
|
|
29
|
-
set:
|
|
39
|
+
create: defaultMutationValidate,
|
|
40
|
+
createMany: defaultMutationValidate,
|
|
41
|
+
update: defaultMutationValidate,
|
|
42
|
+
updateMany: defaultMutationValidate,
|
|
43
|
+
set: defaultMutationValidate,
|
|
30
44
|
remove: commonValidators_1.validateRemove,
|
|
31
45
|
removeMany: commonValidators_1.validateRemoveMany,
|
|
32
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
|
+
*/
|
|
33
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
|
+
*/
|
|
34
76
|
class BaseCore {
|
|
35
77
|
measureTool = new utils_1.MeasureTool();
|
|
36
78
|
config;
|
|
37
79
|
logger;
|
|
38
80
|
constructor(props) {
|
|
39
81
|
this.config = props || {};
|
|
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.
|
|
40
85
|
this.logger = localLogger;
|
|
41
|
-
if ((0,
|
|
86
|
+
if (this.config.logger && (0, utils_1.isLogger)(this.config.logger)) {
|
|
42
87
|
this.logger = this.config.logger;
|
|
43
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).
|
|
44
93
|
this.config.doAuthOnAction = {
|
|
45
|
-
list: props?.doAuthOnAction?.list != null ? props
|
|
46
|
-
get: props?.doAuthOnAction?.get != null ? props
|
|
47
|
-
getMany: props?.doAuthOnAction?.getMany != null ? props
|
|
48
|
-
create: props?.doAuthOnAction?.create != null ? props
|
|
49
|
-
createMany: props?.doAuthOnAction?.createMany != null ? props
|
|
50
|
-
update: props?.doAuthOnAction?.update != null ? props
|
|
51
|
-
updateMany: props?.doAuthOnAction?.updateMany != null ? props
|
|
52
|
-
set: props?.doAuthOnAction?.set != null ? props
|
|
53
|
-
remove: props?.doAuthOnAction?.remove != null ? props
|
|
54
|
-
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,
|
|
55
104
|
};
|
|
56
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
|
+
*/
|
|
57
111
|
getIdType() {
|
|
58
112
|
return this.config.idType ?? constants_1.ID_TYPES.UNKNOWN;
|
|
59
113
|
}
|
|
114
|
+
/**
|
|
115
|
+
* Returns the Database instance from config.
|
|
116
|
+
* Used for transaction management and raw query access.
|
|
117
|
+
*/
|
|
60
118
|
getDb() {
|
|
61
119
|
return this.config.db;
|
|
62
120
|
}
|
|
121
|
+
/**
|
|
122
|
+
* Returns the requestId from the current ApiContext.
|
|
123
|
+
* Used to detect same-request calls (see `sameRequest` logic in runAction).
|
|
124
|
+
*/
|
|
63
125
|
getRequestId() {
|
|
64
126
|
return this.config.context.requestId;
|
|
65
127
|
}
|
|
128
|
+
/**
|
|
129
|
+
* Returns the full ApiContext for this request.
|
|
130
|
+
* Contains userId, spaceId, gateways, cores, headers, etc.
|
|
131
|
+
*/
|
|
66
132
|
getContext() {
|
|
67
133
|
return this.config.context;
|
|
68
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
|
+
*/
|
|
69
139
|
getGateways() {
|
|
70
|
-
return this.config.context
|
|
140
|
+
return this.config.context?.gateways || {};
|
|
71
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
|
+
*/
|
|
72
147
|
getGateway(name) {
|
|
73
|
-
|
|
148
|
+
const gwName = name || this.config.gatewayName;
|
|
149
|
+
return gwName && this.getGateways()?.[gwName];
|
|
74
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
|
+
*/
|
|
75
162
|
getValidators() {
|
|
76
163
|
return defaultValidators;
|
|
77
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
|
+
*/
|
|
78
174
|
success(data, code) {
|
|
79
175
|
const code2use = code != null ? code : api_helpers_1.OP_RESULT_CODES.OK;
|
|
80
176
|
let data2use = data;
|
|
81
177
|
if (!Array.isArray(data2use)) {
|
|
82
|
-
|
|
83
|
-
data2use = [data];
|
|
84
|
-
}
|
|
85
|
-
else {
|
|
86
|
-
data2use = [];
|
|
87
|
-
}
|
|
178
|
+
data2use = data ? [data] : [];
|
|
88
179
|
}
|
|
89
180
|
return new api_helpers_1.OpResult({
|
|
90
181
|
code: code2use,
|
|
@@ -92,20 +183,36 @@ class BaseCore {
|
|
|
92
183
|
errors: [],
|
|
93
184
|
}).toJS();
|
|
94
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
|
+
*/
|
|
95
193
|
failure(code, errorMsg, data) {
|
|
96
194
|
const result = new api_helpers_1.OpResult({ data });
|
|
97
195
|
result.addError('', errorMsg, code);
|
|
98
196
|
return result.toJS();
|
|
99
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
|
+
*/
|
|
100
208
|
validationFailure(ex) {
|
|
101
209
|
const result = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED });
|
|
102
|
-
if ((0,
|
|
210
|
+
if ((0, api_helpers_1.isOpResult)(ex)) {
|
|
103
211
|
return result.toJS();
|
|
104
212
|
}
|
|
105
213
|
Object.keys(ex?.errors || {}).forEach((key) => {
|
|
106
214
|
const obj = ex.errors[key];
|
|
107
215
|
if (Array.isArray(obj.errors)) {
|
|
108
|
-
// if we have multiple rules failures the add them all
|
|
109
216
|
obj.errors.forEach((item) => {
|
|
110
217
|
result.addError(key, item.message);
|
|
111
218
|
});
|
|
@@ -116,23 +223,51 @@ class BaseCore {
|
|
|
116
223
|
});
|
|
117
224
|
return result.toJS();
|
|
118
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
|
+
*/
|
|
119
240
|
exceptionFailure(ex, doingWhat, data) {
|
|
120
241
|
const [isDbError, dbErrorMsg] = this.getDb().isDbError(ex);
|
|
121
|
-
|
|
122
|
-
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;
|
|
123
245
|
const sysMsg = `An exception has occurred on ${doingWhat} with message ${message}:`;
|
|
124
|
-
let msg
|
|
246
|
+
let msg;
|
|
125
247
|
if (isDbError) {
|
|
248
|
+
// DB errors are safe to surface — they come from the DB driver, not app logic
|
|
126
249
|
msg = dbErrorMsg;
|
|
127
250
|
}
|
|
128
251
|
else {
|
|
129
|
-
|
|
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}`;
|
|
130
254
|
this.logger.error(sysMsg, ex);
|
|
131
255
|
}
|
|
132
256
|
const result = new api_helpers_1.OpResult({ data });
|
|
133
257
|
result.addError('', msg, api_helpers_1.OP_RESULT_CODES.EXCEPTION);
|
|
134
258
|
return result.toJS();
|
|
135
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
|
+
*/
|
|
136
271
|
async checkResult(args) {
|
|
137
272
|
const { hasTransaction, result, sameRequest, doingWhat, skipCheckResult } = args;
|
|
138
273
|
if (sameRequest) {
|
|
@@ -160,15 +295,38 @@ class BaseCore {
|
|
|
160
295
|
}
|
|
161
296
|
}
|
|
162
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
|
+
*/
|
|
163
325
|
async runAction(opt) {
|
|
164
|
-
const { args, validate, doAuth, roles, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace, skipCheckResult, } = opt || {};
|
|
165
|
-
//
|
|
166
|
-
//
|
|
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.
|
|
167
329
|
const sameRequest = !!this.config.context.requestId && args?.requestId === this.config.context.requestId;
|
|
168
|
-
// TODO: Calculate total thread block time between async calls withing the request
|
|
169
|
-
// this.measureTool.threadBlockTime(doingWhat, ({ name, durationMs }: any) => {
|
|
170
|
-
// this.logger.debug(`The ${name} blocked thread for the time of ${durationMs} ms`);
|
|
171
|
-
// });
|
|
172
330
|
if (shouldLogArgs == null || shouldLogArgs === true) {
|
|
173
331
|
this.logger.debug(`The ${doingWhat} started:`, args);
|
|
174
332
|
}
|
|
@@ -177,6 +335,8 @@ class BaseCore {
|
|
|
177
335
|
}
|
|
178
336
|
this.measureTool.start();
|
|
179
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.
|
|
180
340
|
const setStep = (stepName) => {
|
|
181
341
|
step = stepName || step;
|
|
182
342
|
const time = this.measureTool.addCheckpoint(stepName);
|
|
@@ -207,7 +367,21 @@ class BaseCore {
|
|
|
207
367
|
return result;
|
|
208
368
|
}
|
|
209
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
|
+
}
|
|
210
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.
|
|
211
385
|
this.measureTool.addCheckpoint('Find space: start');
|
|
212
386
|
const [spaceResult, errMsg] = await this.findSpace();
|
|
213
387
|
this.measureTool.addCheckpoint('Find space: end');
|
|
@@ -219,9 +393,9 @@ class BaseCore {
|
|
|
219
393
|
}
|
|
220
394
|
}
|
|
221
395
|
}
|
|
222
|
-
//
|
|
223
|
-
//
|
|
224
|
-
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) {
|
|
225
399
|
const userRoleId = this.getContext().roleId || '';
|
|
226
400
|
if (!userRoleId) {
|
|
227
401
|
return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FORBIDDEN, [], 'User has not assigned role');
|
|
@@ -233,21 +407,22 @@ class BaseCore {
|
|
|
233
407
|
let validatedItems = {};
|
|
234
408
|
if (typeof validate === 'function') {
|
|
235
409
|
this.measureTool.addCheckpoint('Validate parameters: start');
|
|
236
|
-
//
|
|
237
|
-
//
|
|
238
|
-
//
|
|
239
|
-
//
|
|
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.
|
|
240
417
|
const valideResult = await validate(args, actionOpt);
|
|
241
418
|
let result = valideResult;
|
|
242
419
|
if (Array.isArray(valideResult)) {
|
|
243
420
|
result = valideResult[0];
|
|
244
421
|
validatedItems = valideResult[1] || {};
|
|
245
422
|
}
|
|
246
|
-
// If validator returned null then consider the validation passed
|
|
247
423
|
result = result != null ? result : true;
|
|
248
424
|
this.measureTool.addCheckpoint('Validate parameters: end');
|
|
249
425
|
if (result !== true) {
|
|
250
|
-
// if there was an error then `result` is expected to be an object with the same structure as the checkit library does
|
|
251
426
|
await this.checkResult({ hasTransaction, result, sameRequest });
|
|
252
427
|
return result.code != null ? result : new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED });
|
|
253
428
|
}
|
|
@@ -263,10 +438,12 @@ class BaseCore {
|
|
|
263
438
|
catch (ex) {
|
|
264
439
|
this.logger.error(`An exception has occurred on ${step}:`, ex);
|
|
265
440
|
if (!sameRequest && hasTransaction) {
|
|
266
|
-
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`);
|
|
267
442
|
await this.getDb().rollbackTransaction();
|
|
268
443
|
}
|
|
269
|
-
|
|
444
|
+
// Initialise to doingWhat so context is preserved even if the
|
|
445
|
+
// exception handler itself throws.
|
|
446
|
+
let errMessage;
|
|
270
447
|
try {
|
|
271
448
|
errMessage = await this.onException(args, { ...actionOpt, doingWhat, exception: ex });
|
|
272
449
|
if (check_types_1.default.function(onException)) {
|
|
@@ -274,7 +451,10 @@ class BaseCore {
|
|
|
274
451
|
}
|
|
275
452
|
}
|
|
276
453
|
catch (ex2) {
|
|
277
|
-
|
|
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;
|
|
278
458
|
}
|
|
279
459
|
if (!errMessage) {
|
|
280
460
|
errMessage = doingWhat;
|
|
@@ -287,6 +467,13 @@ class BaseCore {
|
|
|
287
467
|
return this.exceptionFailure(ex, errMessage);
|
|
288
468
|
}
|
|
289
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
|
+
*/
|
|
290
477
|
async list(args) {
|
|
291
478
|
return this.runAction({
|
|
292
479
|
args,
|
|
@@ -296,18 +483,27 @@ class BaseCore {
|
|
|
296
483
|
accessRights: [utils_1.ACCESS_RIGHTS.LIST],
|
|
297
484
|
action: async (args, opt) => {
|
|
298
485
|
const object = await this.beforeList(args, opt);
|
|
299
|
-
if ((0,
|
|
486
|
+
if ((0, api_helpers_1.isOpResult)(object)) {
|
|
300
487
|
return object;
|
|
301
488
|
}
|
|
302
|
-
const items = await this.
|
|
489
|
+
const items = await this.getGateway()?.list(object);
|
|
303
490
|
const result = await this.afterList(items, opt);
|
|
304
|
-
// ON NO DATA RETURN EMPTY CODE
|
|
305
491
|
return this.success(result);
|
|
306
492
|
},
|
|
307
493
|
hasTransaction: false,
|
|
308
494
|
doingWhat: this.config.doingWhat?.list ?? this.config.name ?? 'listing',
|
|
309
495
|
});
|
|
310
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
|
+
*/
|
|
311
507
|
async get(args) {
|
|
312
508
|
return this.runAction({
|
|
313
509
|
args,
|
|
@@ -317,13 +513,13 @@ class BaseCore {
|
|
|
317
513
|
accessRights: [utils_1.ACCESS_RIGHTS.GET],
|
|
318
514
|
action: async (args, opt) => {
|
|
319
515
|
const args2use = await this.beforeGet(args, opt);
|
|
320
|
-
if ((0,
|
|
516
|
+
if ((0, api_helpers_1.isOpResult)(args2use)) {
|
|
321
517
|
return args2use;
|
|
322
518
|
}
|
|
323
519
|
if (args2use?.id == null) {
|
|
324
520
|
return this.failure(api_helpers_1.OP_RESULT_CODES.NOT_FOUND, '', []);
|
|
325
521
|
}
|
|
326
|
-
const item = await this.
|
|
522
|
+
const item = await this.getGateway()?.get(args2use.id);
|
|
327
523
|
const result = await this.afterGet(item, opt);
|
|
328
524
|
if (!result) {
|
|
329
525
|
return this.failure(api_helpers_1.OP_RESULT_CODES.NOT_FOUND, '', []);
|
|
@@ -334,6 +530,16 @@ class BaseCore {
|
|
|
334
530
|
doingWhat: this.config.doingWhat?.get ?? this.config.name ?? 'getting an item',
|
|
335
531
|
});
|
|
336
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
|
+
*/
|
|
337
543
|
async getMany(args) {
|
|
338
544
|
return this.runAction({
|
|
339
545
|
args,
|
|
@@ -343,26 +549,41 @@ class BaseCore {
|
|
|
343
549
|
accessRights: [utils_1.ACCESS_RIGHTS.GET],
|
|
344
550
|
action: async (args, opt) => {
|
|
345
551
|
const args2use = await this.beforeGetMany(args, opt);
|
|
346
|
-
if ((0,
|
|
552
|
+
if ((0, api_helpers_1.isOpResult)(args2use)) {
|
|
347
553
|
return args2use;
|
|
348
554
|
}
|
|
349
555
|
if (!Array.isArray(args2use?.ids)) {
|
|
350
|
-
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', []);
|
|
351
557
|
}
|
|
352
|
-
const items = await this.
|
|
558
|
+
const items = await this.getGateway()?.getMany(args2use.ids);
|
|
353
559
|
const result = await this.afterGetMany(items, opt);
|
|
354
560
|
return this.success(result);
|
|
355
561
|
},
|
|
356
562
|
hasTransaction: false,
|
|
357
|
-
doingWhat: this.config.doingWhat?.getMany ?? this.config.name ?? '
|
|
563
|
+
doingWhat: this.config.doingWhat?.getMany ?? this.config.name ?? 'getting multiple items',
|
|
358
564
|
});
|
|
359
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
|
+
*/
|
|
360
570
|
getGatewayToSetOrerNo() {
|
|
361
|
-
return this.
|
|
571
|
+
return this.getGateway();
|
|
362
572
|
}
|
|
363
|
-
|
|
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) {
|
|
364
579
|
return {};
|
|
365
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
|
+
*/
|
|
366
587
|
async create(args) {
|
|
367
588
|
return this.runAction({
|
|
368
589
|
args,
|
|
@@ -380,10 +601,10 @@ class BaseCore {
|
|
|
380
601
|
});
|
|
381
602
|
}
|
|
382
603
|
const object = await this.beforeCreate(params, opt);
|
|
383
|
-
if ((0,
|
|
604
|
+
if ((0, api_helpers_1.isOpResult)(object)) {
|
|
384
605
|
return object;
|
|
385
606
|
}
|
|
386
|
-
const items = await this.
|
|
607
|
+
const items = await this.getGateway()?.create(object);
|
|
387
608
|
const result = await this.afterCreate(items, opt);
|
|
388
609
|
return this.success(result);
|
|
389
610
|
},
|
|
@@ -391,6 +612,13 @@ class BaseCore {
|
|
|
391
612
|
doingWhat: this.config.doingWhat?.create ?? this.config.name ?? 'creating an item',
|
|
392
613
|
});
|
|
393
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
|
+
*/
|
|
394
622
|
async createMany(args) {
|
|
395
623
|
return this.runAction({
|
|
396
624
|
args,
|
|
@@ -401,10 +629,10 @@ class BaseCore {
|
|
|
401
629
|
action: async (args, opt) => {
|
|
402
630
|
const { params } = args || {};
|
|
403
631
|
const objects = await this.beforeCreateMany(params, opt);
|
|
404
|
-
if ((0,
|
|
632
|
+
if ((0, api_helpers_1.isOpResult)(objects)) {
|
|
405
633
|
return objects;
|
|
406
634
|
}
|
|
407
|
-
const items = await this.
|
|
635
|
+
const items = await this.getGateway()?.create(objects);
|
|
408
636
|
const result = await this.afterCreateMany(items, opt);
|
|
409
637
|
return this.success(result);
|
|
410
638
|
},
|
|
@@ -412,6 +640,16 @@ class BaseCore {
|
|
|
412
640
|
doingWhat: this.config.doingWhat?.createMany ?? this.config.name ?? 'creating multiple items',
|
|
413
641
|
});
|
|
414
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
|
+
*/
|
|
415
653
|
async update(args) {
|
|
416
654
|
return this.runAction({
|
|
417
655
|
args,
|
|
@@ -422,10 +660,10 @@ class BaseCore {
|
|
|
422
660
|
action: async (args, opt) => {
|
|
423
661
|
const { where, params } = args || {};
|
|
424
662
|
const object = await this.beforeUpdate(params, opt);
|
|
425
|
-
if ((0,
|
|
663
|
+
if ((0, api_helpers_1.isOpResult)(object)) {
|
|
426
664
|
return object;
|
|
427
665
|
}
|
|
428
|
-
const items = await this.
|
|
666
|
+
const items = await this.getGateway()?.update(where, object);
|
|
429
667
|
const result = await this.afterUpdate(items, opt);
|
|
430
668
|
return this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND);
|
|
431
669
|
},
|
|
@@ -433,6 +671,13 @@ class BaseCore {
|
|
|
433
671
|
doingWhat: this.config.doingWhat?.update ?? this.config.name ?? 'updating an item',
|
|
434
672
|
});
|
|
435
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
|
+
*/
|
|
436
681
|
async updateMany(args) {
|
|
437
682
|
return this.runAction({
|
|
438
683
|
args,
|
|
@@ -443,10 +688,10 @@ class BaseCore {
|
|
|
443
688
|
action: async (args, opt) => {
|
|
444
689
|
const { params } = args || {};
|
|
445
690
|
const object = await this.beforeUpdateMany(params, opt);
|
|
446
|
-
if ((0,
|
|
691
|
+
if ((0, api_helpers_1.isOpResult)(object)) {
|
|
447
692
|
return object;
|
|
448
693
|
}
|
|
449
|
-
const items = await this.
|
|
694
|
+
const items = await this.getGateway()?.updateMany(object);
|
|
450
695
|
const result = await this.afterUpdateMany(items, opt);
|
|
451
696
|
return this.success(result);
|
|
452
697
|
},
|
|
@@ -454,6 +699,14 @@ class BaseCore {
|
|
|
454
699
|
doingWhat: this.config.doingWhat?.updateMany ?? this.config.name ?? 'updating multiple items',
|
|
455
700
|
});
|
|
456
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
|
+
*/
|
|
457
710
|
async set(args) {
|
|
458
711
|
return this.runAction({
|
|
459
712
|
args,
|
|
@@ -461,20 +714,27 @@ class BaseCore {
|
|
|
461
714
|
actionName: constants_1.ACTIONS.SET,
|
|
462
715
|
validate: this.getValidators().set,
|
|
463
716
|
accessRights: [utils_1.ACCESS_RIGHTS.CREATE, utils_1.ACCESS_RIGHTS.UPDATE],
|
|
464
|
-
action: async (args, opt
|
|
717
|
+
action: async (args, opt) => {
|
|
465
718
|
const { params } = args || {};
|
|
466
719
|
const object = await this.beforeSet(params, opt);
|
|
467
|
-
if ((0,
|
|
720
|
+
if ((0, api_helpers_1.isOpResult)(object)) {
|
|
468
721
|
return object;
|
|
469
722
|
}
|
|
470
|
-
const items = await this.
|
|
723
|
+
const items = await this.getGateway()?.set(object);
|
|
471
724
|
const result = await this.afterSet(items, opt);
|
|
472
725
|
return this.success(result);
|
|
473
726
|
},
|
|
474
727
|
hasTransaction: true,
|
|
475
|
-
doingWhat: this.config.doingWhat?.
|
|
728
|
+
doingWhat: this.config.doingWhat?.set ?? this.config.name ?? 'setting items',
|
|
476
729
|
});
|
|
477
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
|
+
*/
|
|
478
738
|
async remove(args) {
|
|
479
739
|
return this.runAction({
|
|
480
740
|
args,
|
|
@@ -485,10 +745,10 @@ class BaseCore {
|
|
|
485
745
|
action: async (args, opt) => {
|
|
486
746
|
const { where } = args || {};
|
|
487
747
|
const object = await this.beforeRemove(where, opt);
|
|
488
|
-
if ((0,
|
|
748
|
+
if ((0, api_helpers_1.isOpResult)(object)) {
|
|
489
749
|
return object;
|
|
490
750
|
}
|
|
491
|
-
const items = await this.
|
|
751
|
+
const items = await this.getGateway()?.remove(object);
|
|
492
752
|
const result = await this.afterRemove(items, opt);
|
|
493
753
|
return this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND);
|
|
494
754
|
},
|
|
@@ -496,6 +756,13 @@ class BaseCore {
|
|
|
496
756
|
doingWhat: this.config.doingWhat?.remove ?? this.config.name ?? 'removing an item',
|
|
497
757
|
});
|
|
498
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
|
+
*/
|
|
499
766
|
async removeMany(args) {
|
|
500
767
|
return this.runAction({
|
|
501
768
|
args,
|
|
@@ -506,10 +773,10 @@ class BaseCore {
|
|
|
506
773
|
action: async (args, opt) => {
|
|
507
774
|
const { where } = args || {};
|
|
508
775
|
const object = await this.beforeRemoveMany(where, opt);
|
|
509
|
-
if ((0,
|
|
776
|
+
if ((0, api_helpers_1.isOpResult)(object)) {
|
|
510
777
|
return object;
|
|
511
778
|
}
|
|
512
|
-
const items = await this.
|
|
779
|
+
const items = await this.getGateway()?.remove(object);
|
|
513
780
|
const result = await this.afterRemoveMany(items, opt);
|
|
514
781
|
return this.success(result, result.length > 0 ? api_helpers_1.OP_RESULT_CODES.OK : api_helpers_1.OP_RESULT_CODES.NOT_FOUND);
|
|
515
782
|
},
|
|
@@ -517,107 +784,238 @@ class BaseCore {
|
|
|
517
784
|
doingWhat: this.config.doingWhat?.removeMany ?? this.config.name ?? 'removing multiple items',
|
|
518
785
|
});
|
|
519
786
|
}
|
|
520
|
-
|
|
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) {
|
|
521
799
|
return params;
|
|
522
800
|
}
|
|
523
801
|
/**
|
|
524
|
-
*
|
|
525
|
-
*
|
|
526
|
-
*
|
|
527
|
-
* @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.
|
|
528
805
|
*/
|
|
529
|
-
processItemOnOut(item, opt) {
|
|
806
|
+
async processItemOnOut(item, opt) {
|
|
530
807
|
return this.defaultAfterAndBefore(item, opt);
|
|
531
808
|
}
|
|
532
809
|
/**
|
|
533
|
-
*
|
|
534
|
-
*
|
|
535
|
-
*
|
|
536
|
-
* @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.
|
|
537
813
|
*/
|
|
538
|
-
processItemOnIn(item, opt) {
|
|
814
|
+
async processItemOnIn(item, opt) {
|
|
539
815
|
return this.defaultAfterAndBefore(item, opt);
|
|
540
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
|
+
*/
|
|
541
822
|
async beforeGet(item, opt) {
|
|
542
823
|
return this.defaultAfterAndBefore(item, opt);
|
|
543
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
|
+
*/
|
|
544
830
|
async beforeGetMany(items, opt) {
|
|
545
831
|
return this.defaultAfterAndBefore(items, opt);
|
|
546
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
|
+
*/
|
|
547
838
|
async beforeList(filter, opt) {
|
|
548
839
|
return this.defaultAfterAndBefore(filter, opt);
|
|
549
840
|
}
|
|
841
|
+
/**
|
|
842
|
+
* Transforms a single fetched record after get().
|
|
843
|
+
* Delegates to `processItemOnOut()`.
|
|
844
|
+
*/
|
|
550
845
|
async afterGet(item, opt) {
|
|
551
846
|
return this.processItemOnOut(item, opt);
|
|
552
847
|
}
|
|
848
|
+
/**
|
|
849
|
+
* Transforms fetched records after getMany().
|
|
850
|
+
* Maps each item through `processItemOnOut()` using Promise.all
|
|
851
|
+
* to correctly handle async transforms.
|
|
852
|
+
*/
|
|
553
853
|
async afterGetMany(items, opt) {
|
|
554
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
854
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
555
855
|
}
|
|
856
|
+
/**
|
|
857
|
+
* Transforms fetched records after list().
|
|
858
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
859
|
+
*/
|
|
556
860
|
async afterList(items, opt) {
|
|
557
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
861
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
558
862
|
}
|
|
863
|
+
/**
|
|
864
|
+
* Transforms a single record before create().
|
|
865
|
+
* Delegates to `processItemOnIn()`.
|
|
866
|
+
*/
|
|
559
867
|
async beforeCreate(params, opt) {
|
|
560
868
|
return this.processItemOnIn(params, opt);
|
|
561
869
|
}
|
|
870
|
+
/**
|
|
871
|
+
* Transforms created records after create().
|
|
872
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
873
|
+
*/
|
|
562
874
|
async afterCreate(items, opt) {
|
|
563
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
875
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
564
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
|
+
*/
|
|
565
885
|
async beforeCreateMany(items, opt) {
|
|
566
|
-
return items.map((item) => this.processItemOnIn(item, opt));
|
|
886
|
+
return Promise.all(items.map((item) => this.processItemOnIn(item, opt)));
|
|
567
887
|
}
|
|
888
|
+
/**
|
|
889
|
+
* Transforms created records after createMany().
|
|
890
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
891
|
+
*/
|
|
568
892
|
async afterCreateMany(items, opt) {
|
|
569
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
893
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
570
894
|
}
|
|
895
|
+
/**
|
|
896
|
+
* Transforms a single record before update().
|
|
897
|
+
* Delegates to `processItemOnIn()`.
|
|
898
|
+
*/
|
|
571
899
|
async beforeUpdate(params, opt) {
|
|
572
900
|
return this.processItemOnIn(params, opt);
|
|
573
901
|
}
|
|
902
|
+
/**
|
|
903
|
+
* Transforms updated records after update().
|
|
904
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
905
|
+
*/
|
|
574
906
|
async afterUpdate(items, opt) {
|
|
575
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
907
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
576
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
|
+
*/
|
|
577
917
|
async beforeUpdateMany(items, opt) {
|
|
578
|
-
return items.map((item) => {
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
};
|
|
583
|
-
});
|
|
918
|
+
return Promise.all(items.map(async (item) => ({
|
|
919
|
+
params: await this.processItemOnIn(item.params, opt),
|
|
920
|
+
where: item.where,
|
|
921
|
+
})));
|
|
584
922
|
}
|
|
923
|
+
/**
|
|
924
|
+
* Transforms updated records after updateMany().
|
|
925
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
926
|
+
*/
|
|
585
927
|
async afterUpdateMany(items, opt) {
|
|
586
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
928
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
587
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
|
+
*/
|
|
588
938
|
async beforeSet(params, opt) {
|
|
589
|
-
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)));
|
|
590
940
|
}
|
|
941
|
+
/**
|
|
942
|
+
* Transforms upserted records after set().
|
|
943
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
944
|
+
*/
|
|
591
945
|
async afterSet(items, opt) {
|
|
592
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
946
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
593
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
|
+
*/
|
|
594
953
|
async beforeRemove(params, opt) {
|
|
595
954
|
return this.defaultAfterAndBefore(params, opt);
|
|
596
955
|
}
|
|
956
|
+
/**
|
|
957
|
+
* Transforms removed records after remove().
|
|
958
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
959
|
+
*/
|
|
597
960
|
async afterRemove(items, opt) {
|
|
598
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
961
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
599
962
|
}
|
|
963
|
+
/**
|
|
964
|
+
* Transforms the where filter before removeMany().
|
|
965
|
+
* Same contract as beforeRemove() but for bulk removal.
|
|
966
|
+
*/
|
|
600
967
|
async beforeRemoveMany(params, opt) {
|
|
601
968
|
return this.defaultAfterAndBefore(params, opt);
|
|
602
969
|
}
|
|
970
|
+
/**
|
|
971
|
+
* Transforms removed records after removeMany().
|
|
972
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
973
|
+
*/
|
|
603
974
|
async afterRemoveMany(items, opt) {
|
|
604
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
975
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
605
976
|
}
|
|
606
|
-
|
|
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) {
|
|
607
986
|
return '';
|
|
608
987
|
}
|
|
609
988
|
/**
|
|
610
|
-
* Returns JWT secret and
|
|
611
|
-
*
|
|
612
|
-
*
|
|
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
|
|
613
996
|
*/
|
|
614
|
-
async getJwtTokenSecretAndSettings(
|
|
997
|
+
async getJwtTokenSecretAndSettings(_params) {
|
|
615
998
|
const { space } = this.getContext();
|
|
616
999
|
return {
|
|
617
1000
|
jwtSecret: space?.tokenSecret || this.config.jwtSecret || '',
|
|
618
1001
|
verifyTokenArgs: this.config.verifyTokenArgs,
|
|
619
1002
|
};
|
|
620
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
|
+
*/
|
|
621
1019
|
async findSpace() {
|
|
622
1020
|
const { context } = this.config;
|
|
623
1021
|
if (context.space) {
|
|
@@ -628,7 +1026,6 @@ class BaseCore {
|
|
|
628
1026
|
if (!context.spaceId) {
|
|
629
1027
|
return [false, 'Space not specified'];
|
|
630
1028
|
}
|
|
631
|
-
// Lookup space in case we have gateway
|
|
632
1029
|
space = await context.spaceGw.get(context.spaceId || '');
|
|
633
1030
|
if (!space) {
|
|
634
1031
|
return [false, 'Space not found'];
|
|
@@ -637,17 +1034,55 @@ class BaseCore {
|
|
|
637
1034
|
}
|
|
638
1035
|
return [true, space];
|
|
639
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
|
+
*/
|
|
640
1054
|
async extractCredentials(args) {
|
|
641
1055
|
const { req, space, authorization } = args;
|
|
642
1056
|
const token = req.cookies?.[space.cookieName] || req.headers?.[constants_1.HEADERS.AUTHORIZATION] || authorization;
|
|
643
1057
|
const fingerprint = req.cookies?.[space.fingerprintCookieName] || req.headers?.[constants_1.HEADERS.FINGERPRINT] || args.fingerprint || '';
|
|
644
|
-
return {
|
|
645
|
-
token,
|
|
646
|
-
fingerprint,
|
|
647
|
-
};
|
|
1058
|
+
return { token, fingerprint };
|
|
648
1059
|
}
|
|
649
|
-
|
|
650
|
-
|
|
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) {
|
|
651
1086
|
const context = this.getContext();
|
|
652
1087
|
const { req, authorization } = context;
|
|
653
1088
|
let authByToken = false;
|
|
@@ -679,12 +1114,15 @@ class BaseCore {
|
|
|
679
1114
|
context.roleId = tokenData.roleId;
|
|
680
1115
|
context.userId = tokenData.userId;
|
|
681
1116
|
context.isSuperAdmin = context.roleId === 'superadmin';
|
|
682
|
-
|
|
683
|
-
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 || '';
|
|
684
1121
|
authByToken = true;
|
|
685
1122
|
}
|
|
686
1123
|
if (!authByToken) {
|
|
687
1124
|
if (this.config.interserviceApiKey && context.apiKey === this.config.interserviceApiKey) {
|
|
1125
|
+
// Interservice call — trusted API key for service-to-service communication
|
|
688
1126
|
return [true, ''];
|
|
689
1127
|
}
|
|
690
1128
|
else if (space?.apiKey && space?.apiKey !== context.apiKey) {
|
|
@@ -694,16 +1132,37 @@ class BaseCore {
|
|
|
694
1132
|
}
|
|
695
1133
|
return [true, ''];
|
|
696
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
|
+
*/
|
|
697
1143
|
processRemovedRecord(record) {
|
|
698
1144
|
if (record && typeof record.id === 'string') {
|
|
699
1145
|
record.id = record.id.split('~')[0];
|
|
700
1146
|
}
|
|
701
1147
|
return record;
|
|
702
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
|
+
*/
|
|
703
1161
|
addRemovedModifierToFields(fields) {
|
|
704
1162
|
const obj = {};
|
|
705
1163
|
if (!fields) {
|
|
706
|
-
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);
|
|
707
1166
|
return obj;
|
|
708
1167
|
}
|
|
709
1168
|
(0, lodash_1.castArray)(fields).forEach((field) => {
|
|
@@ -711,18 +1170,40 @@ class BaseCore {
|
|
|
711
1170
|
});
|
|
712
1171
|
return obj;
|
|
713
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
|
+
*/
|
|
714
1194
|
async setOrderNo(args) {
|
|
715
1195
|
const { params, filter, gateway } = args || {};
|
|
716
1196
|
if (typeof params !== 'object') {
|
|
717
|
-
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)}`);
|
|
718
1198
|
}
|
|
719
1199
|
if (typeof gateway !== 'object') {
|
|
720
|
-
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)}`);
|
|
721
1201
|
}
|
|
722
1202
|
if (typeof gateway.list !== 'function') {
|
|
723
|
-
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)}`);
|
|
724
1204
|
}
|
|
725
|
-
|
|
1205
|
+
// Fix: use == null instead of falsy check so orderNo: 0 is not overwritten
|
|
1206
|
+
if (params.orderNo == null) {
|
|
726
1207
|
const lastRecord = await gateway.list({
|
|
727
1208
|
filter,
|
|
728
1209
|
params: {
|
|
@@ -734,7 +1215,7 @@ class BaseCore {
|
|
|
734
1215
|
if (this.config.orderNoAsDecimal === true) {
|
|
735
1216
|
params.orderNo =
|
|
736
1217
|
lastRecord[0]?.orderNo != null
|
|
737
|
-
? Number(lastRecord[0]
|
|
1218
|
+
? Number(lastRecord[0].orderNo) + Number(constants_1.DEFAULT_ORDER_NO_STEP)
|
|
738
1219
|
: Number(constants_1.DEFAULT_ORDER_NO);
|
|
739
1220
|
}
|
|
740
1221
|
else {
|