@sdflc/backend-helpers 1.0.112 → 1.0.114
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 +586 -33
- package/build/BaseCore.js +821 -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/IpRateLimiter.d.ts +105 -0
- package/build/IpRateLimiter.js +104 -0
- package/build/RedisDataLoader.d.ts +144 -21
- package/build/RedisDataLoader.js +178 -49
- package/build/apiContext.d.ts +0 -8
- package/build/apiContext.js +30 -32
- 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 +586 -33
- package/build/esm/BaseCore.js +812 -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/IpRateLimiter.d.ts +105 -0
- package/build/esm/IpRateLimiter.js +100 -0
- 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 +30 -32
- 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 +6 -2
- package/build/esm/index.js +6 -2
- package/build/esm/interfaces/ApiContext.d.ts +33 -3
- package/build/esm/interfaces/ApiContext.js +1 -0
- 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 +146 -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 +60 -0
- package/build/esm/interfaces/CoreActionInterface.js +1 -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 +6 -2
- package/build/index.js +6 -2
- package/build/interfaces/ApiContext.d.ts +33 -3
- package/build/interfaces/ApiContext.js +1 -0
- 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 +146 -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 +60 -0
- package/build/interfaces/CoreActionInterface.js +1 -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/esm/BaseCore.js
CHANGED
|
@@ -1,84 +1,202 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
1
|
+
// ./src/BaseCore.ts
|
|
2
|
+
import { OpResult, OP_RESULT_CODES, isOpResult } from '@sdflc/api-helpers';
|
|
3
|
+
import { Logger, ACCESS_RIGHTS, MeasureTool, StrOrderHelpers, LoggerLevels, isLogger } from '@sdflc/utils';
|
|
3
4
|
import check from 'check-types';
|
|
4
5
|
import { castArray } from 'lodash';
|
|
5
6
|
import { validateGet, validateGetMany, validateRemove, validateRemoveMany } from './commonValidators';
|
|
6
7
|
import { ACTIONS, DEFAULT_ORDER_NO, DEFAULT_ORDER_NO_STEP, FIELDS, HEADERS, ID_TYPES, ORDER_BYS } from './constants';
|
|
7
8
|
import { getDefaultJwtAlgorithm, getDefaultJwtIssuer, verifyUserToken } from './userToken';
|
|
8
|
-
|
|
9
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Default no-op validator — allows all operations through without checks.
|
|
11
|
+
* Used as the fallback for action types that do not define custom validation.
|
|
12
|
+
*/
|
|
13
|
+
const defaultValidate = () => {
|
|
10
14
|
return [true, {}];
|
|
11
15
|
};
|
|
12
|
-
|
|
16
|
+
/**
|
|
17
|
+
* Default no-op validator for mutation operations (create, update, set).
|
|
18
|
+
* Kept separate from defaultValidate so subclasses can override mutation
|
|
19
|
+
* validation independently of read validation if needed.
|
|
20
|
+
*/
|
|
21
|
+
const defaultMutationValidate = () => {
|
|
13
22
|
return [true, {}];
|
|
14
23
|
};
|
|
24
|
+
/**
|
|
25
|
+
* Default validator map applied to all actions unless overridden via `getValidators()`.
|
|
26
|
+
* Read operations (get, getMany) use stricter built-in validators that check
|
|
27
|
+
* for required id fields. Mutations use the permissive no-op default.
|
|
28
|
+
*/
|
|
15
29
|
const defaultValidators = {
|
|
16
30
|
list: defaultValidate,
|
|
17
31
|
get: validateGet,
|
|
18
32
|
getMany: validateGetMany,
|
|
19
|
-
create:
|
|
20
|
-
createMany:
|
|
21
|
-
update:
|
|
22
|
-
updateMany:
|
|
23
|
-
set:
|
|
33
|
+
create: defaultMutationValidate,
|
|
34
|
+
createMany: defaultMutationValidate,
|
|
35
|
+
update: defaultMutationValidate,
|
|
36
|
+
updateMany: defaultMutationValidate,
|
|
37
|
+
set: defaultMutationValidate,
|
|
24
38
|
remove: validateRemove,
|
|
25
39
|
removeMany: validateRemoveMany,
|
|
26
40
|
};
|
|
41
|
+
/**
|
|
42
|
+
* Module-level logger used as the initial fallback before the instance logger
|
|
43
|
+
* is resolved from config. Set to ERROR level to suppress noise during construction.
|
|
44
|
+
*/
|
|
27
45
|
const localLogger = new Logger({ level: LoggerLevels.ERROR });
|
|
46
|
+
/**
|
|
47
|
+
* BaseCore is the foundation for all business-logic core classes.
|
|
48
|
+
*
|
|
49
|
+
* A core sits between the transport layer (GraphQL resolvers, REST controllers)
|
|
50
|
+
* and the data layer (gateways). It is responsible for:
|
|
51
|
+
* - Authentication and authorisation (via `runAction`)
|
|
52
|
+
* - Input validation (via validator functions)
|
|
53
|
+
* - Database transaction management
|
|
54
|
+
* - Calling gateway methods and transforming results
|
|
55
|
+
* - Consistent error handling and OpResult wrapping
|
|
56
|
+
* - Optional IP-based rate limiting (via `checkRateLimit`)
|
|
57
|
+
*
|
|
58
|
+
* Cores are instantiated per-request and receive a full `BaseCorePropsInterface`
|
|
59
|
+
* including the ApiContext, db, logger, auth config, and optional rate-limit config.
|
|
60
|
+
*
|
|
61
|
+
* Rate limiting runs two independent tiers, both must pass:
|
|
62
|
+
*
|
|
63
|
+
* Global tier — context.globalRateLimit, set once at app startup.
|
|
64
|
+
* Always counted when present; cannot be opted out.
|
|
65
|
+
* Guards the whole service from a flood regardless of
|
|
66
|
+
* which action the IP targets.
|
|
67
|
+
*
|
|
68
|
+
* Core-or-action tier — mutually exclusive; action rule replaces core rule:
|
|
69
|
+
* 1. CoreActionInterface.rateLimit (per-call override)
|
|
70
|
+
* 2. rateLimitOnAction[actionName] (per-action props)
|
|
71
|
+
* 3. config.rateLimit (core-level default)
|
|
72
|
+
* false at step 1 or 2 disables this tier for that
|
|
73
|
+
* action (only global applies). Raising an action limit
|
|
74
|
+
* above the core default works correctly because the
|
|
75
|
+
* core counter is not also running.
|
|
76
|
+
*
|
|
77
|
+
* To wire up: create one IpRateLimiter at app startup, set it on context.rateLimiter.
|
|
78
|
+
* To use a custom limiter: pass `rateLimiter` (any RateLimiterInterface).
|
|
79
|
+
* To disable: pass `rateLimiter: null`.
|
|
80
|
+
*
|
|
81
|
+
* Rule resolution order (first match wins):
|
|
82
|
+
* CoreActionInterface.rateLimit
|
|
83
|
+
* → BaseCorePropsInterface.rateLimitOnAction[actionName]
|
|
84
|
+
* → BaseCorePropsInterface.rateLimit
|
|
85
|
+
* → no limiting
|
|
86
|
+
*
|
|
87
|
+
* Subclasses typically override:
|
|
88
|
+
* - `getValidators()` — to provide custom validation per action
|
|
89
|
+
* - `before*` / `after*` — to transform inputs/outputs per action
|
|
90
|
+
* - `processItemOnIn()` — to normalise inbound data
|
|
91
|
+
* - `processItemOnOut()` — to shape outbound data
|
|
92
|
+
* - `authenticate()` — to implement custom auth strategies
|
|
93
|
+
* - `getJwtTokenSecretAndSettings()` — to resolve JWT config per space/tenant
|
|
94
|
+
* - `onException()` — to customise exception messages
|
|
95
|
+
* - `getFilterToSetOrderNo()` — to scope orderNo sequences to a parent entity
|
|
96
|
+
*/
|
|
28
97
|
class BaseCore {
|
|
29
98
|
measureTool = new MeasureTool();
|
|
30
99
|
config;
|
|
31
100
|
logger;
|
|
32
101
|
constructor(props) {
|
|
33
102
|
this.config = props || {};
|
|
103
|
+
// Start with the module-level fallback logger, then upgrade to the
|
|
104
|
+
// configured one if it passes the duck-type check.
|
|
105
|
+
// Duck-type check avoids instanceof failures across package versions.
|
|
34
106
|
this.logger = localLogger;
|
|
35
|
-
if (isLogger(this.config.logger)) {
|
|
107
|
+
if (this.config.logger && isLogger(this.config.logger)) {
|
|
36
108
|
this.logger = this.config.logger;
|
|
37
109
|
}
|
|
110
|
+
// Resolve per-action auth flags. Each action can independently enable or
|
|
111
|
+
// disable auth via doAuthOnAction. If not explicitly set for an action,
|
|
112
|
+
// it falls back to the top-level doAuth flag. This allows a core to
|
|
113
|
+
// require auth globally while exempting specific actions (e.g. list).
|
|
38
114
|
this.config.doAuthOnAction = {
|
|
39
|
-
list: props?.doAuthOnAction?.list != null ? props
|
|
40
|
-
get: props?.doAuthOnAction?.get != null ? props
|
|
41
|
-
getMany: props?.doAuthOnAction?.getMany != null ? props
|
|
42
|
-
create: props?.doAuthOnAction?.create != null ? props
|
|
43
|
-
createMany: props?.doAuthOnAction?.createMany != null ? props
|
|
44
|
-
update: props?.doAuthOnAction?.update != null ? props
|
|
45
|
-
updateMany: props?.doAuthOnAction?.updateMany != null ? props
|
|
46
|
-
set: props?.doAuthOnAction?.set != null ? props
|
|
47
|
-
remove: props?.doAuthOnAction?.remove != null ? props
|
|
48
|
-
removeMany: props?.doAuthOnAction?.removeMany != null ? props
|
|
115
|
+
list: props?.doAuthOnAction?.list != null ? props.doAuthOnAction.list : props?.doAuth,
|
|
116
|
+
get: props?.doAuthOnAction?.get != null ? props.doAuthOnAction.get : props?.doAuth,
|
|
117
|
+
getMany: props?.doAuthOnAction?.getMany != null ? props.doAuthOnAction.getMany : props?.doAuth,
|
|
118
|
+
create: props?.doAuthOnAction?.create != null ? props.doAuthOnAction.create : props?.doAuth,
|
|
119
|
+
createMany: props?.doAuthOnAction?.createMany != null ? props.doAuthOnAction.createMany : props?.doAuth,
|
|
120
|
+
update: props?.doAuthOnAction?.update != null ? props.doAuthOnAction.update : props?.doAuth,
|
|
121
|
+
updateMany: props?.doAuthOnAction?.updateMany != null ? props.doAuthOnAction.updateMany : props?.doAuth,
|
|
122
|
+
set: props?.doAuthOnAction?.set != null ? props.doAuthOnAction.set : props?.doAuth,
|
|
123
|
+
remove: props?.doAuthOnAction?.remove != null ? props.doAuthOnAction.remove : props?.doAuth,
|
|
124
|
+
removeMany: props?.doAuthOnAction?.removeMany != null ? props.doAuthOnAction.removeMany : props?.doAuth,
|
|
49
125
|
};
|
|
50
126
|
}
|
|
127
|
+
/**
|
|
128
|
+
* Returns the ID type this core operates with (UUID, integer, etc.).
|
|
129
|
+
* Defaults to ID_TYPES.UNKNOWN if not configured.
|
|
130
|
+
* Used by consumers that need to validate or coerce ID formats.
|
|
131
|
+
*/
|
|
51
132
|
getIdType() {
|
|
52
133
|
return this.config.idType ?? ID_TYPES.UNKNOWN;
|
|
53
134
|
}
|
|
135
|
+
/**
|
|
136
|
+
* Returns the Database instance from config.
|
|
137
|
+
* Used for transaction management and raw query access.
|
|
138
|
+
*/
|
|
54
139
|
getDb() {
|
|
55
140
|
return this.config.db;
|
|
56
141
|
}
|
|
142
|
+
/**
|
|
143
|
+
* Returns the requestId from the current ApiContext.
|
|
144
|
+
* Used to detect same-request calls (see `sameRequest` logic in runAction).
|
|
145
|
+
*/
|
|
57
146
|
getRequestId() {
|
|
58
147
|
return this.config.context.requestId;
|
|
59
148
|
}
|
|
149
|
+
/**
|
|
150
|
+
* Returns the full ApiContext for this request.
|
|
151
|
+
* Contains userId, spaceId, gateways, cores, headers, etc.
|
|
152
|
+
*/
|
|
60
153
|
getContext() {
|
|
61
154
|
return this.config.context;
|
|
62
155
|
}
|
|
156
|
+
/**
|
|
157
|
+
* Returns all gateway instances from the current request context.
|
|
158
|
+
* Returns an empty object if context or gateways are not available.
|
|
159
|
+
*/
|
|
63
160
|
getGateways() {
|
|
64
|
-
return this.config.context
|
|
161
|
+
return this.config.context?.gateways || {};
|
|
65
162
|
}
|
|
163
|
+
/**
|
|
164
|
+
* Returns a single gateway by name.
|
|
165
|
+
* Falls back to `config.gatewayName` if no name is provided.
|
|
166
|
+
* Returns undefined if the gateway does not exist in context.
|
|
167
|
+
*/
|
|
66
168
|
getGateway(name) {
|
|
67
|
-
|
|
169
|
+
const gwName = name || this.config.gatewayName;
|
|
170
|
+
return gwName && this.getGateways()?.[gwName];
|
|
68
171
|
}
|
|
172
|
+
/**
|
|
173
|
+
* Returns the validator map for this core.
|
|
174
|
+
* Override in subclasses to provide custom validators per action.
|
|
175
|
+
*
|
|
176
|
+
* Each validator is a function (or async function) that receives
|
|
177
|
+
* `(args, actionOpt)` and returns `[result, validatedItems]` where:
|
|
178
|
+
* - result === true means validation passed
|
|
179
|
+
* - result is a validation error object if validation failed
|
|
180
|
+
* - validatedItems is an optional object of pre-fetched/validated data
|
|
181
|
+
* that will be merged into actionOpt for the action handler
|
|
182
|
+
*/
|
|
69
183
|
getValidators() {
|
|
70
184
|
return defaultValidators;
|
|
71
185
|
}
|
|
186
|
+
/**
|
|
187
|
+
* Wraps data in a successful OpResult and returns its plain JS representation.
|
|
188
|
+
*
|
|
189
|
+
* Always returns data as an array — single objects are wrapped in `[data]`.
|
|
190
|
+
* Empty/null data returns an empty array with OK status.
|
|
191
|
+
*
|
|
192
|
+
* @param data The data to include in the result
|
|
193
|
+
* @param code Optional result code (defaults to OP_RESULT_CODES.OK)
|
|
194
|
+
*/
|
|
72
195
|
success(data, code) {
|
|
73
196
|
const code2use = code != null ? code : OP_RESULT_CODES.OK;
|
|
74
197
|
let data2use = data;
|
|
75
198
|
if (!Array.isArray(data2use)) {
|
|
76
|
-
|
|
77
|
-
data2use = [data];
|
|
78
|
-
}
|
|
79
|
-
else {
|
|
80
|
-
data2use = [];
|
|
81
|
-
}
|
|
199
|
+
data2use = data ? [data] : [];
|
|
82
200
|
}
|
|
83
201
|
return new OpResult({
|
|
84
202
|
code: code2use,
|
|
@@ -86,11 +204,28 @@ class BaseCore {
|
|
|
86
204
|
errors: [],
|
|
87
205
|
}).toJS();
|
|
88
206
|
}
|
|
207
|
+
/**
|
|
208
|
+
* Creates a failed OpResult with a single error message.
|
|
209
|
+
*
|
|
210
|
+
* @param code Result code (e.g. OP_RESULT_CODES.NOT_FOUND)
|
|
211
|
+
* @param errorMsg Human-readable error description
|
|
212
|
+
* @param data Optional data payload to include alongside the error
|
|
213
|
+
*/
|
|
89
214
|
failure(code, errorMsg, data) {
|
|
90
215
|
const result = new OpResult({ data });
|
|
91
216
|
result.addError('', errorMsg, code);
|
|
92
217
|
return result.toJS();
|
|
93
218
|
}
|
|
219
|
+
/**
|
|
220
|
+
* Creates a validation-failed OpResult from a validation error object.
|
|
221
|
+
*
|
|
222
|
+
* Handles two cases:
|
|
223
|
+
* - If `ex` is already an OpResult, returns a plain VALIDATION_FAILED result
|
|
224
|
+
* (the original OpResult's errors are not re-wrapped to avoid duplication)
|
|
225
|
+
* - Otherwise, iterates `ex.errors` (checkit library format) and adds each
|
|
226
|
+
* field's error messages individually, supporting both single and multiple
|
|
227
|
+
* rule failures per field
|
|
228
|
+
*/
|
|
94
229
|
validationFailure(ex) {
|
|
95
230
|
const result = new OpResult({ code: OP_RESULT_CODES.VALIDATION_FAILED });
|
|
96
231
|
if (isOpResult(ex)) {
|
|
@@ -99,7 +234,6 @@ class BaseCore {
|
|
|
99
234
|
Object.keys(ex?.errors || {}).forEach((key) => {
|
|
100
235
|
const obj = ex.errors[key];
|
|
101
236
|
if (Array.isArray(obj.errors)) {
|
|
102
|
-
// if we have multiple rules failures the add them all
|
|
103
237
|
obj.errors.forEach((item) => {
|
|
104
238
|
result.addError(key, item.message);
|
|
105
239
|
});
|
|
@@ -110,23 +244,51 @@ class BaseCore {
|
|
|
110
244
|
});
|
|
111
245
|
return result.toJS();
|
|
112
246
|
}
|
|
247
|
+
/**
|
|
248
|
+
* Creates an exception-failed OpResult from a caught error.
|
|
249
|
+
*
|
|
250
|
+
* Distinguishes between database errors (returned to the client with the
|
|
251
|
+
* DB-level message) and application errors (logged internally, generic
|
|
252
|
+
* message returned to the client to avoid leaking implementation details).
|
|
253
|
+
*
|
|
254
|
+
* Note: uses `isExOpResult` instead of `isOpResult` to avoid shadowing
|
|
255
|
+
* the imported `isOpResult` utility function.
|
|
256
|
+
*
|
|
257
|
+
* @param ex The caught exception
|
|
258
|
+
* @param doingWhat Description of the operation that failed (for logging)
|
|
259
|
+
* @param data Optional data payload to include in the result
|
|
260
|
+
*/
|
|
113
261
|
exceptionFailure(ex, doingWhat, data) {
|
|
114
262
|
const [isDbError, dbErrorMsg] = this.getDb().isDbError(ex);
|
|
115
|
-
|
|
116
|
-
const
|
|
263
|
+
// Renamed from `isOpResult` to avoid shadowing the imported utility
|
|
264
|
+
const isExOpResult = typeof ex.getErrorSummary === 'function';
|
|
265
|
+
const message = isExOpResult ? ex.getErrorSummary() : ex.message;
|
|
117
266
|
const sysMsg = `An exception has occurred on ${doingWhat} with message ${message}:`;
|
|
118
|
-
let msg
|
|
267
|
+
let msg;
|
|
119
268
|
if (isDbError) {
|
|
269
|
+
// DB errors are safe to surface — they come from the DB driver, not app logic
|
|
120
270
|
msg = dbErrorMsg;
|
|
121
271
|
}
|
|
122
272
|
else {
|
|
123
|
-
|
|
273
|
+
// Non-DB errors: log the full detail internally, return a safe generic message
|
|
274
|
+
msg = isExOpResult ? ex.getErrorSummary() : `Sorry, something went wrong on ${doingWhat}`;
|
|
124
275
|
this.logger.error(sysMsg, ex);
|
|
125
276
|
}
|
|
126
277
|
const result = new OpResult({ data });
|
|
127
278
|
result.addError('', msg, OP_RESULT_CODES.EXCEPTION);
|
|
128
279
|
return result.toJS();
|
|
129
280
|
}
|
|
281
|
+
/**
|
|
282
|
+
* Commits or rolls back the active database transaction based on the action result.
|
|
283
|
+
*
|
|
284
|
+
* Called at the end of every `runAction()` flow, including in the catch block.
|
|
285
|
+
* Does nothing if `hasTransaction` is false or if `sameRequest` is true
|
|
286
|
+
* (same-request calls share their caller's transaction).
|
|
287
|
+
*
|
|
288
|
+
* `skipCheckResult` forces a commit regardless of result code — useful for
|
|
289
|
+
* operations where the caller has already verified correctness and just needs
|
|
290
|
+
* the transaction closed (e.g. after a manual rollback-and-retry pattern).
|
|
291
|
+
*/
|
|
130
292
|
async checkResult(args) {
|
|
131
293
|
const { hasTransaction, result, sameRequest, doingWhat, skipCheckResult } = args;
|
|
132
294
|
if (sameRequest) {
|
|
@@ -154,15 +316,210 @@ class BaseCore {
|
|
|
154
316
|
}
|
|
155
317
|
}
|
|
156
318
|
}
|
|
319
|
+
/**
|
|
320
|
+
* Returns the active rate-limiter for this request.
|
|
321
|
+
*
|
|
322
|
+
* Resolution order (first defined value wins):
|
|
323
|
+
* 1. config.rateLimiter — per-core override; null explicitly disables
|
|
324
|
+
* 2. context.rateLimiter — app-level singleton set at startup
|
|
325
|
+
* 3. null — no limiting
|
|
326
|
+
*
|
|
327
|
+
* The app-level instance on context is created once at startup (e.g. in
|
|
328
|
+
* your context factory alongside spaceGw, globalRateLimit, etc.) and shared
|
|
329
|
+
* across all cores in all requests. This avoids creating a new limiter
|
|
330
|
+
* object on every request while still allowing individual cores to swap
|
|
331
|
+
* in a custom implementation or disable limiting entirely via config.
|
|
332
|
+
*/
|
|
333
|
+
getRateLimiter() {
|
|
334
|
+
// 1. Per-core explicit override (including null to disable for this core)
|
|
335
|
+
if (this.config.rateLimiter !== undefined) {
|
|
336
|
+
return this.config.rateLimiter ?? null;
|
|
337
|
+
}
|
|
338
|
+
// 2. App-level singleton from context
|
|
339
|
+
const contextLimiter = this.getContext().rateLimiter;
|
|
340
|
+
if (contextLimiter !== undefined) {
|
|
341
|
+
return contextLimiter ?? null;
|
|
342
|
+
}
|
|
343
|
+
// 3. Nothing configured — no limiting
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Collects the rate-limit rules that apply to a single runAction call.
|
|
348
|
+
*
|
|
349
|
+
* Returns at most two entries: one for the global tier and one for the
|
|
350
|
+
* core-or-action tier. Both tiers are independent — each gets its own
|
|
351
|
+
* Redis counter and the request must pass both to proceed.
|
|
352
|
+
*
|
|
353
|
+
* ── Global tier ─────────────────────────────────────────────────────────
|
|
354
|
+
* Sourced from context.globalRateLimit. Always included when present —
|
|
355
|
+
* it cannot be opted out by core or action configuration. This is the
|
|
356
|
+
* service-wide flood guard: no single IP can saturate the service
|
|
357
|
+
* regardless of which action it targets.
|
|
358
|
+
*
|
|
359
|
+
* ── Core-or-action tier (mutually exclusive) ────────────────────────────
|
|
360
|
+
* Core and action rules are NOT additive. If an action-level rule exists
|
|
361
|
+
* it completely replaces the core rule for that action. This makes
|
|
362
|
+
* loosening or tightening a single action meaningful: raising the action
|
|
363
|
+
* limit actually raises it (the core counter will not block first), and
|
|
364
|
+
* lowering it tightens that specific action without affecting others.
|
|
365
|
+
*
|
|
366
|
+
* Resolution for the core-or-action tier (first defined value wins):
|
|
367
|
+
* 1. callOverride (CoreActionInterface.rateLimit)
|
|
368
|
+
* 2. rateLimitOnAction[actionName]
|
|
369
|
+
* 3. config.rateLimit (core-level default)
|
|
370
|
+
* 4. nothing — tier omitted
|
|
371
|
+
*
|
|
372
|
+
* false at step 1 or 2 explicitly disables this tier for the action
|
|
373
|
+
* so only the global counter applies. false never suppresses global.
|
|
374
|
+
*
|
|
375
|
+
* @param actionName Stable action key used for per-action lookup and as
|
|
376
|
+
* the Redis key segment when rule.action is not set.
|
|
377
|
+
* @param callOverride The rateLimit value passed directly to runAction().
|
|
378
|
+
*/
|
|
379
|
+
collectRateLimitRules(actionName, callOverride) {
|
|
380
|
+
const collected = [];
|
|
381
|
+
// ── Global tier ──────────────────────────────────────────────────────────
|
|
382
|
+
// Always added when present. No opt-out — this is the service-wide guard.
|
|
383
|
+
const globalRule = this.getContext().globalRateLimit;
|
|
384
|
+
if (globalRule) {
|
|
385
|
+
collected.push({ rule: globalRule, scope: 'global' });
|
|
386
|
+
}
|
|
387
|
+
// ── Core-or-action tier ──────────────────────────────────────────────────
|
|
388
|
+
// Walk the resolution chain. The first defined value (including false) wins
|
|
389
|
+
// and stops the search — core and action are mutually exclusive so that a
|
|
390
|
+
// raised action limit is not silently capped by the core counter.
|
|
391
|
+
// Step 1: per-call override (highest priority)
|
|
392
|
+
let tierRule = callOverride;
|
|
393
|
+
// Step 2: per-action props (only when no call-site override was given)
|
|
394
|
+
if (tierRule === undefined && actionName && this.config.rateLimitOnAction) {
|
|
395
|
+
tierRule = this.config.rateLimitOnAction[actionName];
|
|
396
|
+
}
|
|
397
|
+
// Step 3: core-level default (only when no action-level rule was found)
|
|
398
|
+
if (tierRule === undefined && this.config.rateLimit) {
|
|
399
|
+
tierRule = this.config.rateLimit;
|
|
400
|
+
}
|
|
401
|
+
// false means "disable the core-or-action tier for this action" —
|
|
402
|
+
// only the global counter applies. Omitted entirely from collected.
|
|
403
|
+
if (tierRule !== undefined && tierRule !== false) {
|
|
404
|
+
collected.push({ rule: tierRule, scope: 'core-action' });
|
|
405
|
+
}
|
|
406
|
+
return collected;
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Checks applicable rate-limit counters for the current request.
|
|
410
|
+
*
|
|
411
|
+
* Called at the very start of runAction(), before the DB transaction is
|
|
412
|
+
* opened and before any authentication, so auth endpoints are protected
|
|
413
|
+
* from brute-force without any DB or session overhead.
|
|
414
|
+
*
|
|
415
|
+
* Runs up to two independent counters in parallel (global + core-or-action).
|
|
416
|
+
* The request is blocked if either counter is exceeded.
|
|
417
|
+
*
|
|
418
|
+
* Returns an OpResult with code TOO_MANY_REQUESTS (429) on the first block
|
|
419
|
+
* found, or null when the request may proceed.
|
|
420
|
+
*
|
|
421
|
+
* Never throws — any error from the limiter is treated as "allow" to ensure
|
|
422
|
+
* Redis unavailability cannot take down an endpoint.
|
|
423
|
+
*
|
|
424
|
+
* Skipped entirely when:
|
|
425
|
+
* - No rules are collected for this action (collectRateLimitRules returns [])
|
|
426
|
+
* - No limiter is available (no context.rateLimiter, no config.rateLimiter)
|
|
427
|
+
* - sameRequest is true (nested calls within the same request are not
|
|
428
|
+
* re-counted — the outer call has already consumed the slot)
|
|
429
|
+
*
|
|
430
|
+
* Redis key format per tier:
|
|
431
|
+
* rl:{spaceId}:{scope}:{actionKey}:{ip}
|
|
432
|
+
* The scope segment ('global' or 'core-action') keeps the two counters in
|
|
433
|
+
* separate keys so they never interfere with each other.
|
|
434
|
+
*
|
|
435
|
+
* @param actionName Stable action identifier used as the Redis key segment
|
|
436
|
+
* and for per-action rule lookup.
|
|
437
|
+
* @param callOverride The rateLimit value passed to the current runAction call.
|
|
438
|
+
* @param doingWhat Human-readable description used in log messages.
|
|
439
|
+
*/
|
|
440
|
+
async checkRateLimit(actionName, callOverride, doingWhat) {
|
|
441
|
+
const rules = this.collectRateLimitRules(actionName, callOverride);
|
|
442
|
+
if (rules.length === 0) {
|
|
443
|
+
// Nothing to check — skip limiter lookup entirely
|
|
444
|
+
return null;
|
|
445
|
+
}
|
|
446
|
+
const limiter = this.getRateLimiter();
|
|
447
|
+
if (!limiter) {
|
|
448
|
+
// No limiter available (no context.rateLimiter, no config.rateLimiter) — allow through
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
const context = this.getContext();
|
|
452
|
+
const ip = context.ipAddress || '';
|
|
453
|
+
const spaceId = context.spaceId || '';
|
|
454
|
+
// Stable key segment: prefer rule.action override, then actionName, then doingWhat
|
|
455
|
+
const actionKey = actionName || doingWhat;
|
|
456
|
+
this.logger.debug(`Checking ${rules.length} rate-limit counter(s) for action '${actionKey}' from IP '${ip}' in space '${spaceId}' on ${doingWhat}`);
|
|
457
|
+
// Run all counters in parallel — every applicable level is incremented on
|
|
458
|
+
// every request regardless of what the others return. This ensures counters
|
|
459
|
+
// stay accurate even when the request is ultimately blocked by another level.
|
|
460
|
+
const results = await Promise.all(rules.map(({ rule, scope }) => limiter.check({
|
|
461
|
+
// Scope prefix keeps counters for different levels in separate keys
|
|
462
|
+
action: `${scope}:${rule.action || actionKey}`,
|
|
463
|
+
ip,
|
|
464
|
+
spaceId,
|
|
465
|
+
limit: rule.limit,
|
|
466
|
+
windowSec: rule.windowSec,
|
|
467
|
+
})));
|
|
468
|
+
// Find the first blocked result and return it; allow if all passed
|
|
469
|
+
for (let i = 0; i < results.length; i++) {
|
|
470
|
+
const result = results[i];
|
|
471
|
+
const { scope } = rules[i];
|
|
472
|
+
if (result.blocked) {
|
|
473
|
+
const retryAfter = result.ttlSec > 0 ? ` Please try again in ${result.ttlSec} seconds.` : '';
|
|
474
|
+
const msg = `Too many requests.${retryAfter}`;
|
|
475
|
+
this.logger.log(`Rate limit blocked action '${actionKey}' for IP '${ip}' in space '${spaceId}' on ${doingWhat}: ${scope} counter exceeded (${result.count} requests in window)`);
|
|
476
|
+
const opResult = new OpResult({ code: OP_RESULT_CODES.TOO_MANY_REQUESTS });
|
|
477
|
+
opResult.addError('', msg, OP_RESULT_CODES.TOO_MANY_REQUESTS);
|
|
478
|
+
return opResult;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return null;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Core action runner. All public CRUD methods delegate to this.
|
|
485
|
+
*
|
|
486
|
+
* Execution flow:
|
|
487
|
+
* 1. Detect same-request calls (skip transaction + auth + rate limiting for
|
|
488
|
+
* nested calls within the same request, identified by matching requestId)
|
|
489
|
+
* 2. Check IP rate limits if configured — all applicable counters (global,
|
|
490
|
+
* core, action) are checked in parallel; blocked if any is exceeded
|
|
491
|
+
* 3. Start DB transaction if `hasTransaction` is true
|
|
492
|
+
* 4. Authenticate the request (if `doAuth` is true) OR verify the space
|
|
493
|
+
* (if `requireSpace` is not false) — space verification is a lighter
|
|
494
|
+
* alternative to full auth for public-but-space-scoped operations
|
|
495
|
+
* 5. Check role-based access if `roles` array is provided
|
|
496
|
+
* 6. Run the validator function if provided — validator returns
|
|
497
|
+
* `[true, validatedItems]` on success or `[errorObj, {}]` on failure
|
|
498
|
+
* 7. Execute the action handler with `(args, { ...actionOpt, validatedItems })`
|
|
499
|
+
* 8. Commit or rollback the transaction via `checkResult()`
|
|
500
|
+
* 9. On any exception: rollback, call `onException()` and the caller's
|
|
501
|
+
* `onException` hook, then return an exceptionFailure result
|
|
502
|
+
*
|
|
503
|
+
* Same-request detection:
|
|
504
|
+
* When a core method calls another core method on the same request
|
|
505
|
+
* (e.g. create calling list to re-fetch results), it can pass
|
|
506
|
+
* `args.requestId = context.requestId`. The inner call detects this,
|
|
507
|
+
* skips starting a new transaction, skips auth, skips rate limiting,
|
|
508
|
+
* and skips committing — the outer call owns the transaction lifecycle.
|
|
509
|
+
*
|
|
510
|
+
* Rate limiting:
|
|
511
|
+
* Resolved via collectRateLimitRules() and checked via checkRateLimit().
|
|
512
|
+
* See BaseCorePropsInterface for the full rule resolution chain.
|
|
513
|
+
* Entirely skipped if no rateLimiter is configured.
|
|
514
|
+
*
|
|
515
|
+
* @param opt CoreActionInterface with all action configuration
|
|
516
|
+
*/
|
|
157
517
|
async runAction(opt) {
|
|
158
|
-
const { args, validate, doAuth, roles, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace, skipCheckResult, } = opt || {};
|
|
159
|
-
//
|
|
160
|
-
//
|
|
518
|
+
const { args, validate, doAuth, tryAuth, roles, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace, skipCheckResult, actionName, rateLimit: callRateLimit, } = opt || {};
|
|
519
|
+
// Detect if this is a nested call within the same request.
|
|
520
|
+
// If so, skip transaction management, auth, and rate limiting to avoid
|
|
521
|
+
// double-wrapping and double-counting.
|
|
161
522
|
const sameRequest = !!this.config.context.requestId && args?.requestId === this.config.context.requestId;
|
|
162
|
-
// TODO: Calculate total thread block time between async calls withing the request
|
|
163
|
-
// this.measureTool.threadBlockTime(doingWhat, ({ name, durationMs }: any) => {
|
|
164
|
-
// this.logger.debug(`The ${name} blocked thread for the time of ${durationMs} ms`);
|
|
165
|
-
// });
|
|
166
523
|
if (shouldLogArgs == null || shouldLogArgs === true) {
|
|
167
524
|
this.logger.debug(`The ${doingWhat} started:`, args);
|
|
168
525
|
}
|
|
@@ -171,6 +528,8 @@ class BaseCore {
|
|
|
171
528
|
}
|
|
172
529
|
this.measureTool.start();
|
|
173
530
|
let step = doingWhat || '';
|
|
531
|
+
// setStep is passed to action handlers and validators so they can emit
|
|
532
|
+
// granular timing checkpoints that appear in debug logs.
|
|
174
533
|
const setStep = (stepName) => {
|
|
175
534
|
step = stepName || step;
|
|
176
535
|
const time = this.measureTool.addCheckpoint(stepName);
|
|
@@ -185,6 +544,19 @@ class BaseCore {
|
|
|
185
544
|
hasTransaction,
|
|
186
545
|
};
|
|
187
546
|
try {
|
|
547
|
+
// ── Step 1: Rate limiting ──────────────────────────────────────────────
|
|
548
|
+
// Checked before the DB transaction is opened and before authentication.
|
|
549
|
+
// Same-request nested calls are excluded — the outer call was already
|
|
550
|
+
// counted and we must not penalise legitimate internal fan-out.
|
|
551
|
+
if (!sameRequest) {
|
|
552
|
+
this.measureTool.addCheckpoint('Rate limit check: start');
|
|
553
|
+
const rateLimitResult = await this.checkRateLimit(actionName, callRateLimit, doingWhat ?? '');
|
|
554
|
+
this.measureTool.addCheckpoint('Rate limit check: end');
|
|
555
|
+
if (rateLimitResult !== null) {
|
|
556
|
+
// Request is blocked — return immediately, no transaction opened
|
|
557
|
+
return rateLimitResult;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
188
560
|
if (!sameRequest) {
|
|
189
561
|
if (hasTransaction) {
|
|
190
562
|
this.logger.debug(`Start DB transaction on ${step}`);
|
|
@@ -201,7 +573,21 @@ class BaseCore {
|
|
|
201
573
|
return result;
|
|
202
574
|
}
|
|
203
575
|
}
|
|
576
|
+
else if (tryAuth === true) {
|
|
577
|
+
// Soft auth — attempt to populate context from token but never fail.
|
|
578
|
+
// Errors are swallowed intentionally — the request continues either way.
|
|
579
|
+
this.measureTool.addCheckpoint('Try authenticate request: start');
|
|
580
|
+
try {
|
|
581
|
+
await this.authenticate(opt, actionOpt);
|
|
582
|
+
}
|
|
583
|
+
catch (ex) {
|
|
584
|
+
this.logger.debug(`The ${step} soft authentication attempt failed silently:`, ex);
|
|
585
|
+
}
|
|
586
|
+
this.measureTool.addCheckpoint('Try authenticate request: end');
|
|
587
|
+
}
|
|
204
588
|
else if (requireSpace == null || requireSpace === true) {
|
|
589
|
+
// Space verification: lighter than full auth — confirms the request
|
|
590
|
+
// is targeting a known, valid space without verifying user identity.
|
|
205
591
|
this.measureTool.addCheckpoint('Find space: start');
|
|
206
592
|
const [spaceResult, errMsg] = await this.findSpace();
|
|
207
593
|
this.measureTool.addCheckpoint('Find space: end');
|
|
@@ -213,9 +599,9 @@ class BaseCore {
|
|
|
213
599
|
}
|
|
214
600
|
}
|
|
215
601
|
}
|
|
216
|
-
//
|
|
217
|
-
//
|
|
218
|
-
if (Array.isArray(roles) && roles
|
|
602
|
+
// Role check: simpler than full RBAC — verifies the user's roleId is in
|
|
603
|
+
// the allowed list for this action. Checked after auth so roleId is populated.
|
|
604
|
+
if (Array.isArray(roles) && roles.length > 0) {
|
|
219
605
|
const userRoleId = this.getContext().roleId || '';
|
|
220
606
|
if (!userRoleId) {
|
|
221
607
|
return OpResult.fail(OP_RESULT_CODES.FORBIDDEN, [], 'User has not assigned role');
|
|
@@ -227,21 +613,22 @@ class BaseCore {
|
|
|
227
613
|
let validatedItems = {};
|
|
228
614
|
if (typeof validate === 'function') {
|
|
229
615
|
this.measureTool.addCheckpoint('Validate parameters: start');
|
|
230
|
-
//
|
|
231
|
-
//
|
|
232
|
-
//
|
|
233
|
-
//
|
|
616
|
+
// Validator returns [result, validatedItems]:
|
|
617
|
+
// - result === true: validation passed
|
|
618
|
+
// - result === null: treated as passed (some validators return null on success)
|
|
619
|
+
// - result is object: validation failed, object contains error details
|
|
620
|
+
// validatedItems carries any data the validator pre-fetched
|
|
621
|
+
// (e.g. the existing record for an update) so the action handler
|
|
622
|
+
// doesn't need to re-fetch it.
|
|
234
623
|
const valideResult = await validate(args, actionOpt);
|
|
235
624
|
let result = valideResult;
|
|
236
625
|
if (Array.isArray(valideResult)) {
|
|
237
626
|
result = valideResult[0];
|
|
238
627
|
validatedItems = valideResult[1] || {};
|
|
239
628
|
}
|
|
240
|
-
// If validator returned null then consider the validation passed
|
|
241
629
|
result = result != null ? result : true;
|
|
242
630
|
this.measureTool.addCheckpoint('Validate parameters: end');
|
|
243
631
|
if (result !== true) {
|
|
244
|
-
// if there was an error then `result` is expected to be an object with the same structure as the checkit library does
|
|
245
632
|
await this.checkResult({ hasTransaction, result, sameRequest });
|
|
246
633
|
return result.code != null ? result : new OpResult({ code: OP_RESULT_CODES.VALIDATION_FAILED });
|
|
247
634
|
}
|
|
@@ -257,10 +644,12 @@ class BaseCore {
|
|
|
257
644
|
catch (ex) {
|
|
258
645
|
this.logger.error(`An exception has occurred on ${step}:`, ex);
|
|
259
646
|
if (!sameRequest && hasTransaction) {
|
|
260
|
-
this.logger.debug(`Rolling back DB transaction on ${step} due to an
|
|
647
|
+
this.logger.debug(`Rolling back DB transaction on ${step} due to an exception`);
|
|
261
648
|
await this.getDb().rollbackTransaction();
|
|
262
649
|
}
|
|
263
|
-
|
|
650
|
+
// Initialise to doingWhat so context is preserved even if the
|
|
651
|
+
// exception handler itself throws.
|
|
652
|
+
let errMessage;
|
|
264
653
|
try {
|
|
265
654
|
errMessage = await this.onException(args, { ...actionOpt, doingWhat, exception: ex });
|
|
266
655
|
if (check.function(onException)) {
|
|
@@ -268,7 +657,10 @@ class BaseCore {
|
|
|
268
657
|
}
|
|
269
658
|
}
|
|
270
659
|
catch (ex2) {
|
|
271
|
-
|
|
660
|
+
// If the exception handler itself throws, fall back to doingWhat
|
|
661
|
+
// so the outer exceptionFailure still has meaningful context.
|
|
662
|
+
this.logger.error(`An exception has occurred when handling exception:`, ex2);
|
|
663
|
+
errMessage = doingWhat;
|
|
272
664
|
}
|
|
273
665
|
if (!errMessage) {
|
|
274
666
|
errMessage = doingWhat;
|
|
@@ -281,6 +673,13 @@ class BaseCore {
|
|
|
281
673
|
return this.exceptionFailure(ex, errMessage);
|
|
282
674
|
}
|
|
283
675
|
}
|
|
676
|
+
/**
|
|
677
|
+
* Lists records via the configured gateway.
|
|
678
|
+
*
|
|
679
|
+
* Calls `beforeList()` to transform filter args, then `afterList()` on results.
|
|
680
|
+
* Auth is controlled by `doAuthOnAction.list`.
|
|
681
|
+
* Does not use a DB transaction — list is a read-only operation.
|
|
682
|
+
*/
|
|
284
683
|
async list(args) {
|
|
285
684
|
return this.runAction({
|
|
286
685
|
args,
|
|
@@ -293,15 +692,24 @@ class BaseCore {
|
|
|
293
692
|
if (isOpResult(object)) {
|
|
294
693
|
return object;
|
|
295
694
|
}
|
|
296
|
-
const items = await this.
|
|
695
|
+
const items = await this.getGateway()?.list(object);
|
|
297
696
|
const result = await this.afterList(items, opt);
|
|
298
|
-
// ON NO DATA RETURN EMPTY CODE
|
|
299
697
|
return this.success(result);
|
|
300
698
|
},
|
|
301
699
|
hasTransaction: false,
|
|
302
700
|
doingWhat: this.config.doingWhat?.list ?? this.config.name ?? 'listing',
|
|
303
701
|
});
|
|
304
702
|
}
|
|
703
|
+
/**
|
|
704
|
+
* Fetches a single record by id via the configured gateway.
|
|
705
|
+
*
|
|
706
|
+
* Calls `beforeGet()` to transform/validate the args object (which should
|
|
707
|
+
* contain an `id` field). Returns NOT_FOUND if:
|
|
708
|
+
* - beforeGet returns null/undefined id
|
|
709
|
+
* - the gateway returns no record for that id
|
|
710
|
+
*
|
|
711
|
+
* Does not use a DB transaction.
|
|
712
|
+
*/
|
|
305
713
|
async get(args) {
|
|
306
714
|
return this.runAction({
|
|
307
715
|
args,
|
|
@@ -317,7 +725,7 @@ class BaseCore {
|
|
|
317
725
|
if (args2use?.id == null) {
|
|
318
726
|
return this.failure(OP_RESULT_CODES.NOT_FOUND, '', []);
|
|
319
727
|
}
|
|
320
|
-
const item = await this.
|
|
728
|
+
const item = await this.getGateway()?.get(args2use.id);
|
|
321
729
|
const result = await this.afterGet(item, opt);
|
|
322
730
|
if (!result) {
|
|
323
731
|
return this.failure(OP_RESULT_CODES.NOT_FOUND, '', []);
|
|
@@ -328,6 +736,16 @@ class BaseCore {
|
|
|
328
736
|
doingWhat: this.config.doingWhat?.get ?? this.config.name ?? 'getting an item',
|
|
329
737
|
});
|
|
330
738
|
}
|
|
739
|
+
/**
|
|
740
|
+
* Fetches multiple records by their ids via the configured gateway.
|
|
741
|
+
*
|
|
742
|
+
* Calls `beforeGetMany()` to transform the args object (which should
|
|
743
|
+
* contain an `ids` array). Returns NOT_FOUND if `ids` is not an array
|
|
744
|
+
* after the before-hook.
|
|
745
|
+
*
|
|
746
|
+
* Results are returned in DataLoader order (same order as input ids,
|
|
747
|
+
* with null entries for missing records). Does not use a DB transaction.
|
|
748
|
+
*/
|
|
331
749
|
async getMany(args) {
|
|
332
750
|
return this.runAction({
|
|
333
751
|
args,
|
|
@@ -341,22 +759,37 @@ class BaseCore {
|
|
|
341
759
|
return args2use;
|
|
342
760
|
}
|
|
343
761
|
if (!Array.isArray(args2use?.ids)) {
|
|
344
|
-
return this.failure(OP_RESULT_CODES.NOT_FOUND, '', []);
|
|
762
|
+
return this.failure(OP_RESULT_CODES.NOT_FOUND, 'Expected ids array but received invalid input', []);
|
|
345
763
|
}
|
|
346
|
-
const items = await this.
|
|
764
|
+
const items = await this.getGateway()?.getMany(args2use.ids);
|
|
347
765
|
const result = await this.afterGetMany(items, opt);
|
|
348
766
|
return this.success(result);
|
|
349
767
|
},
|
|
350
768
|
hasTransaction: false,
|
|
351
|
-
doingWhat: this.config.doingWhat?.getMany ?? this.config.name ?? '
|
|
769
|
+
doingWhat: this.config.doingWhat?.getMany ?? this.config.name ?? 'getting multiple items',
|
|
352
770
|
});
|
|
353
771
|
}
|
|
772
|
+
/**
|
|
773
|
+
* Returns the gateway instance used for orderNo calculation.
|
|
774
|
+
* Override in subclasses to use a different gateway than the default one.
|
|
775
|
+
*/
|
|
354
776
|
getGatewayToSetOrerNo() {
|
|
355
|
-
return this.
|
|
777
|
+
return this.getGateway();
|
|
356
778
|
}
|
|
357
|
-
|
|
779
|
+
/**
|
|
780
|
+
* Returns the filter object used when querying for the last orderNo value.
|
|
781
|
+
* Override in subclasses to scope orderNo sequences to a parent entity
|
|
782
|
+
* (e.g. return `{ categoryId: params.categoryId }` to have per-category ordering).
|
|
783
|
+
*/
|
|
784
|
+
getFilterToSetOrderNo(_args) {
|
|
358
785
|
return {};
|
|
359
786
|
}
|
|
787
|
+
/**
|
|
788
|
+
* Creates a single record via the configured gateway.
|
|
789
|
+
*
|
|
790
|
+
* If `config.hasOrderNo` is true, auto-calculates the next orderNo value
|
|
791
|
+
* before calling `beforeCreate()`. Uses a DB transaction.
|
|
792
|
+
*/
|
|
360
793
|
async create(args) {
|
|
361
794
|
return this.runAction({
|
|
362
795
|
args,
|
|
@@ -377,7 +810,7 @@ class BaseCore {
|
|
|
377
810
|
if (isOpResult(object)) {
|
|
378
811
|
return object;
|
|
379
812
|
}
|
|
380
|
-
const items = await this.
|
|
813
|
+
const items = await this.getGateway()?.create(object);
|
|
381
814
|
const result = await this.afterCreate(items, opt);
|
|
382
815
|
return this.success(result);
|
|
383
816
|
},
|
|
@@ -385,6 +818,13 @@ class BaseCore {
|
|
|
385
818
|
doingWhat: this.config.doingWhat?.create ?? this.config.name ?? 'creating an item',
|
|
386
819
|
});
|
|
387
820
|
}
|
|
821
|
+
/**
|
|
822
|
+
* Creates multiple records in a single gateway call.
|
|
823
|
+
*
|
|
824
|
+
* Calls `beforeCreateMany()` which maps each item through `processItemOnIn()`
|
|
825
|
+
* using `Promise.all` to correctly resolve async transforms.
|
|
826
|
+
* Uses a DB transaction.
|
|
827
|
+
*/
|
|
388
828
|
async createMany(args) {
|
|
389
829
|
return this.runAction({
|
|
390
830
|
args,
|
|
@@ -398,7 +838,7 @@ class BaseCore {
|
|
|
398
838
|
if (isOpResult(objects)) {
|
|
399
839
|
return objects;
|
|
400
840
|
}
|
|
401
|
-
const items = await this.
|
|
841
|
+
const items = await this.getGateway()?.create(objects);
|
|
402
842
|
const result = await this.afterCreateMany(items, opt);
|
|
403
843
|
return this.success(result);
|
|
404
844
|
},
|
|
@@ -406,6 +846,16 @@ class BaseCore {
|
|
|
406
846
|
doingWhat: this.config.doingWhat?.createMany ?? this.config.name ?? 'creating multiple items',
|
|
407
847
|
});
|
|
408
848
|
}
|
|
849
|
+
/**
|
|
850
|
+
* Updates a single record matching the `where` filter.
|
|
851
|
+
*
|
|
852
|
+
* `args` should contain `{ where, params }`:
|
|
853
|
+
* - `where` carries the filter (id, optional version for optimistic locking)
|
|
854
|
+
* - `params` carries the fields to update
|
|
855
|
+
*
|
|
856
|
+
* Returns NOT_FOUND if the gateway reports 0 affected records.
|
|
857
|
+
* Uses a DB transaction.
|
|
858
|
+
*/
|
|
409
859
|
async update(args) {
|
|
410
860
|
return this.runAction({
|
|
411
861
|
args,
|
|
@@ -419,7 +869,7 @@ class BaseCore {
|
|
|
419
869
|
if (isOpResult(object)) {
|
|
420
870
|
return object;
|
|
421
871
|
}
|
|
422
|
-
const items = await this.
|
|
872
|
+
const items = await this.getGateway()?.update(where, object);
|
|
423
873
|
const result = await this.afterUpdate(items, opt);
|
|
424
874
|
return this.success(result, result.length > 0 ? OP_RESULT_CODES.OK : OP_RESULT_CODES.NOT_FOUND);
|
|
425
875
|
},
|
|
@@ -427,6 +877,13 @@ class BaseCore {
|
|
|
427
877
|
doingWhat: this.config.doingWhat?.update ?? this.config.name ?? 'updating an item',
|
|
428
878
|
});
|
|
429
879
|
}
|
|
880
|
+
/**
|
|
881
|
+
* Updates multiple records, each with its own where/params pair.
|
|
882
|
+
*
|
|
883
|
+
* `args.params` should be an array of `{ where, params }` objects.
|
|
884
|
+
* Each is processed sequentially by the gateway's `updateMany()`.
|
|
885
|
+
* Uses a DB transaction.
|
|
886
|
+
*/
|
|
430
887
|
async updateMany(args) {
|
|
431
888
|
return this.runAction({
|
|
432
889
|
args,
|
|
@@ -440,7 +897,7 @@ class BaseCore {
|
|
|
440
897
|
if (isOpResult(object)) {
|
|
441
898
|
return object;
|
|
442
899
|
}
|
|
443
|
-
const items = await this.
|
|
900
|
+
const items = await this.getGateway()?.updateMany(object);
|
|
444
901
|
const result = await this.afterUpdateMany(items, opt);
|
|
445
902
|
return this.success(result);
|
|
446
903
|
},
|
|
@@ -448,6 +905,14 @@ class BaseCore {
|
|
|
448
905
|
doingWhat: this.config.doingWhat?.updateMany ?? this.config.name ?? 'updating multiple items',
|
|
449
906
|
});
|
|
450
907
|
}
|
|
908
|
+
/**
|
|
909
|
+
* Upserts one or more records via the gateway's `set()` method
|
|
910
|
+
* (INSERT ... ON CONFLICT ... MERGE).
|
|
911
|
+
*
|
|
912
|
+
* `args.params` can be a single object or array. Each item is passed
|
|
913
|
+
* through `processItemOnIn()` via `beforeSet()`.
|
|
914
|
+
* Uses a DB transaction.
|
|
915
|
+
*/
|
|
451
916
|
async set(args) {
|
|
452
917
|
return this.runAction({
|
|
453
918
|
args,
|
|
@@ -455,20 +920,27 @@ class BaseCore {
|
|
|
455
920
|
actionName: ACTIONS.SET,
|
|
456
921
|
validate: this.getValidators().set,
|
|
457
922
|
accessRights: [ACCESS_RIGHTS.CREATE, ACCESS_RIGHTS.UPDATE],
|
|
458
|
-
action: async (args, opt
|
|
923
|
+
action: async (args, opt) => {
|
|
459
924
|
const { params } = args || {};
|
|
460
925
|
const object = await this.beforeSet(params, opt);
|
|
461
926
|
if (isOpResult(object)) {
|
|
462
927
|
return object;
|
|
463
928
|
}
|
|
464
|
-
const items = await this.
|
|
929
|
+
const items = await this.getGateway()?.set(object);
|
|
465
930
|
const result = await this.afterSet(items, opt);
|
|
466
931
|
return this.success(result);
|
|
467
932
|
},
|
|
468
933
|
hasTransaction: true,
|
|
469
|
-
doingWhat: this.config.doingWhat?.
|
|
934
|
+
doingWhat: this.config.doingWhat?.set ?? this.config.name ?? 'setting items',
|
|
470
935
|
});
|
|
471
936
|
}
|
|
937
|
+
/**
|
|
938
|
+
* Soft- or hard-deletes a single record matching `args.where`.
|
|
939
|
+
*
|
|
940
|
+
* The actual delete behaviour (hard vs soft) is determined by gateway config.
|
|
941
|
+
* Returns NOT_FOUND if the gateway reports 0 affected records.
|
|
942
|
+
* Does not use a DB transaction (remove is typically a single atomic operation).
|
|
943
|
+
*/
|
|
472
944
|
async remove(args) {
|
|
473
945
|
return this.runAction({
|
|
474
946
|
args,
|
|
@@ -482,7 +954,7 @@ class BaseCore {
|
|
|
482
954
|
if (isOpResult(object)) {
|
|
483
955
|
return object;
|
|
484
956
|
}
|
|
485
|
-
const items = await this.
|
|
957
|
+
const items = await this.getGateway()?.remove(object);
|
|
486
958
|
const result = await this.afterRemove(items, opt);
|
|
487
959
|
return this.success(result, result.length > 0 ? OP_RESULT_CODES.OK : OP_RESULT_CODES.NOT_FOUND);
|
|
488
960
|
},
|
|
@@ -490,6 +962,13 @@ class BaseCore {
|
|
|
490
962
|
doingWhat: this.config.doingWhat?.remove ?? this.config.name ?? 'removing an item',
|
|
491
963
|
});
|
|
492
964
|
}
|
|
965
|
+
/**
|
|
966
|
+
* Removes multiple records matching `args.where`.
|
|
967
|
+
*
|
|
968
|
+
* Delegates to the gateway's `remove()` method (not `removeMany`) —
|
|
969
|
+
* the gateway's `onRemoveFilter` handles the multi-id WHERE clause.
|
|
970
|
+
* Does not use a DB transaction.
|
|
971
|
+
*/
|
|
493
972
|
async removeMany(args) {
|
|
494
973
|
return this.runAction({
|
|
495
974
|
args,
|
|
@@ -503,7 +982,7 @@ class BaseCore {
|
|
|
503
982
|
if (isOpResult(object)) {
|
|
504
983
|
return object;
|
|
505
984
|
}
|
|
506
|
-
const items = await this.
|
|
985
|
+
const items = await this.getGateway()?.remove(object);
|
|
507
986
|
const result = await this.afterRemoveMany(items, opt);
|
|
508
987
|
return this.success(result, result.length > 0 ? OP_RESULT_CODES.OK : OP_RESULT_CODES.NOT_FOUND);
|
|
509
988
|
},
|
|
@@ -511,107 +990,238 @@ class BaseCore {
|
|
|
511
990
|
doingWhat: this.config.doingWhat?.removeMany ?? this.config.name ?? 'removing multiple items',
|
|
512
991
|
});
|
|
513
992
|
}
|
|
514
|
-
|
|
993
|
+
// ─── Before / After hooks ──────────────────────────────────────────────────
|
|
994
|
+
// These hooks are the primary extension points for subclasses.
|
|
995
|
+
// The before-* hooks transform input before it reaches the gateway.
|
|
996
|
+
// The after-* hooks transform output before it is returned to the caller.
|
|
997
|
+
// All hooks receive `opt: BaseCoreActionsInterface` which includes the core
|
|
998
|
+
// instance, setStep, and any validatedItems from the validator.
|
|
999
|
+
/**
|
|
1000
|
+
* Default identity transform used by all before/after hooks that have
|
|
1001
|
+
* no specific logic. Simply returns the params unchanged.
|
|
1002
|
+
* Override to add cross-cutting transforms that apply to all actions.
|
|
1003
|
+
*/
|
|
1004
|
+
async defaultAfterAndBefore(params, _opt) {
|
|
515
1005
|
return params;
|
|
516
1006
|
}
|
|
517
1007
|
/**
|
|
518
|
-
*
|
|
519
|
-
*
|
|
520
|
-
*
|
|
521
|
-
* @returns {any} transformed object
|
|
1008
|
+
* Transforms an outbound record (from DB to caller).
|
|
1009
|
+
* Override to rename fields, attach computed properties, or strip sensitive data.
|
|
1010
|
+
* Called by all after-* hooks via their Promise.all map loops.
|
|
522
1011
|
*/
|
|
523
|
-
processItemOnOut(item, opt) {
|
|
1012
|
+
async processItemOnOut(item, opt) {
|
|
524
1013
|
return this.defaultAfterAndBefore(item, opt);
|
|
525
1014
|
}
|
|
526
1015
|
/**
|
|
527
|
-
*
|
|
528
|
-
*
|
|
529
|
-
*
|
|
530
|
-
* @returns {any} transformed object
|
|
1016
|
+
* Transforms an inbound record (from caller to DB).
|
|
1017
|
+
* Override to normalise fields, enforce defaults, or coerce types before writes.
|
|
1018
|
+
* Called by all before-* mutation hooks via their Promise.all map loops.
|
|
531
1019
|
*/
|
|
532
|
-
processItemOnIn(item, opt) {
|
|
1020
|
+
async processItemOnIn(item, opt) {
|
|
533
1021
|
return this.defaultAfterAndBefore(item, opt);
|
|
534
1022
|
}
|
|
1023
|
+
/**
|
|
1024
|
+
* Transforms the args object before a get() call.
|
|
1025
|
+
* The returned object should contain an `id` field.
|
|
1026
|
+
* If it returns an OpResult, `get()` will return that OpResult directly.
|
|
1027
|
+
*/
|
|
535
1028
|
async beforeGet(item, opt) {
|
|
536
1029
|
return this.defaultAfterAndBefore(item, opt);
|
|
537
1030
|
}
|
|
1031
|
+
/**
|
|
1032
|
+
* Transforms the args object before a getMany() call.
|
|
1033
|
+
* The returned object should contain an `ids` array.
|
|
1034
|
+
* If it returns an OpResult, `getMany()` will return that OpResult directly.
|
|
1035
|
+
*/
|
|
538
1036
|
async beforeGetMany(items, opt) {
|
|
539
1037
|
return this.defaultAfterAndBefore(items, opt);
|
|
540
1038
|
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Transforms the filter/args object before a list() call.
|
|
1041
|
+
* Override to inject default filters, enforce scope restrictions, etc.
|
|
1042
|
+
* If it returns an OpResult, `list()` will return that OpResult directly.
|
|
1043
|
+
*/
|
|
541
1044
|
async beforeList(filter, opt) {
|
|
542
1045
|
return this.defaultAfterAndBefore(filter, opt);
|
|
543
1046
|
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Transforms a single fetched record after get().
|
|
1049
|
+
* Delegates to `processItemOnOut()`.
|
|
1050
|
+
*/
|
|
544
1051
|
async afterGet(item, opt) {
|
|
545
1052
|
return this.processItemOnOut(item, opt);
|
|
546
1053
|
}
|
|
1054
|
+
/**
|
|
1055
|
+
* Transforms fetched records after getMany().
|
|
1056
|
+
* Maps each item through `processItemOnOut()` using Promise.all
|
|
1057
|
+
* to correctly handle async transforms.
|
|
1058
|
+
*/
|
|
547
1059
|
async afterGetMany(items, opt) {
|
|
548
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
1060
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
549
1061
|
}
|
|
1062
|
+
/**
|
|
1063
|
+
* Transforms fetched records after list().
|
|
1064
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
1065
|
+
*/
|
|
550
1066
|
async afterList(items, opt) {
|
|
551
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
1067
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
552
1068
|
}
|
|
1069
|
+
/**
|
|
1070
|
+
* Transforms a single record before create().
|
|
1071
|
+
* Delegates to `processItemOnIn()`.
|
|
1072
|
+
*/
|
|
553
1073
|
async beforeCreate(params, opt) {
|
|
554
1074
|
return this.processItemOnIn(params, opt);
|
|
555
1075
|
}
|
|
1076
|
+
/**
|
|
1077
|
+
* Transforms created records after create().
|
|
1078
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
1079
|
+
*/
|
|
556
1080
|
async afterCreate(items, opt) {
|
|
557
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
1081
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
558
1082
|
}
|
|
1083
|
+
/**
|
|
1084
|
+
* Transforms an array of records before createMany().
|
|
1085
|
+
* Maps each item through `processItemOnIn()` using Promise.all
|
|
1086
|
+
* to correctly resolve async transforms.
|
|
1087
|
+
*
|
|
1088
|
+
* Fix: was using .map() without Promise.all, returning Promise[]
|
|
1089
|
+
* instead of resolved values.
|
|
1090
|
+
*/
|
|
559
1091
|
async beforeCreateMany(items, opt) {
|
|
560
|
-
return items.map((item) => this.processItemOnIn(item, opt));
|
|
1092
|
+
return Promise.all(items.map((item) => this.processItemOnIn(item, opt)));
|
|
561
1093
|
}
|
|
1094
|
+
/**
|
|
1095
|
+
* Transforms created records after createMany().
|
|
1096
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
1097
|
+
*/
|
|
562
1098
|
async afterCreateMany(items, opt) {
|
|
563
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
1099
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
564
1100
|
}
|
|
1101
|
+
/**
|
|
1102
|
+
* Transforms a single record before update().
|
|
1103
|
+
* Delegates to `processItemOnIn()`.
|
|
1104
|
+
*/
|
|
565
1105
|
async beforeUpdate(params, opt) {
|
|
566
1106
|
return this.processItemOnIn(params, opt);
|
|
567
1107
|
}
|
|
1108
|
+
/**
|
|
1109
|
+
* Transforms updated records after update().
|
|
1110
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
1111
|
+
*/
|
|
568
1112
|
async afterUpdate(items, opt) {
|
|
569
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
1113
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
570
1114
|
}
|
|
1115
|
+
/**
|
|
1116
|
+
* Transforms an array of { where, params } objects before updateMany().
|
|
1117
|
+
* Maps each item's `params` through `processItemOnIn()` while preserving
|
|
1118
|
+
* the `where` filter unchanged.
|
|
1119
|
+
*
|
|
1120
|
+
* Fix: was using .map() without Promise.all, returning Promise[]
|
|
1121
|
+
* instead of resolved values.
|
|
1122
|
+
*/
|
|
571
1123
|
async beforeUpdateMany(items, opt) {
|
|
572
|
-
return items.map((item) => {
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
};
|
|
577
|
-
});
|
|
1124
|
+
return Promise.all(items.map(async (item) => ({
|
|
1125
|
+
params: await this.processItemOnIn(item.params, opt),
|
|
1126
|
+
where: item.where,
|
|
1127
|
+
})));
|
|
578
1128
|
}
|
|
1129
|
+
/**
|
|
1130
|
+
* Transforms updated records after updateMany().
|
|
1131
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
1132
|
+
*/
|
|
579
1133
|
async afterUpdateMany(items, opt) {
|
|
580
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
1134
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
581
1135
|
}
|
|
1136
|
+
/**
|
|
1137
|
+
* Transforms params before set() (upsert).
|
|
1138
|
+
* Normalises params to an array via castArray, then maps each item
|
|
1139
|
+
* through `processItemOnIn()` using Promise.all.
|
|
1140
|
+
*
|
|
1141
|
+
* Fix: was using .map() without Promise.all, returning Promise[]
|
|
1142
|
+
* instead of resolved values.
|
|
1143
|
+
*/
|
|
582
1144
|
async beforeSet(params, opt) {
|
|
583
|
-
return castArray(params).map((item) => this.processItemOnIn(item, opt));
|
|
1145
|
+
return Promise.all(castArray(params).map((item) => this.processItemOnIn(item, opt)));
|
|
584
1146
|
}
|
|
1147
|
+
/**
|
|
1148
|
+
* Transforms upserted records after set().
|
|
1149
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
1150
|
+
*/
|
|
585
1151
|
async afterSet(items, opt) {
|
|
586
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
1152
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
587
1153
|
}
|
|
1154
|
+
/**
|
|
1155
|
+
* Transforms the where filter before remove().
|
|
1156
|
+
* Override to add ownership checks or enrich the filter before deletion.
|
|
1157
|
+
* If it returns an OpResult, `remove()` returns that OpResult directly.
|
|
1158
|
+
*/
|
|
588
1159
|
async beforeRemove(params, opt) {
|
|
589
1160
|
return this.defaultAfterAndBefore(params, opt);
|
|
590
1161
|
}
|
|
1162
|
+
/**
|
|
1163
|
+
* Transforms removed records after remove().
|
|
1164
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
1165
|
+
*/
|
|
591
1166
|
async afterRemove(items, opt) {
|
|
592
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
1167
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
593
1168
|
}
|
|
1169
|
+
/**
|
|
1170
|
+
* Transforms the where filter before removeMany().
|
|
1171
|
+
* Same contract as beforeRemove() but for bulk removal.
|
|
1172
|
+
*/
|
|
594
1173
|
async beforeRemoveMany(params, opt) {
|
|
595
1174
|
return this.defaultAfterAndBefore(params, opt);
|
|
596
1175
|
}
|
|
1176
|
+
/**
|
|
1177
|
+
* Transforms removed records after removeMany().
|
|
1178
|
+
* Maps each item through `processItemOnOut()` using Promise.all.
|
|
1179
|
+
*/
|
|
597
1180
|
async afterRemoveMany(items, opt) {
|
|
598
|
-
return items.map((item) => this.processItemOnOut(item, opt));
|
|
1181
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
599
1182
|
}
|
|
600
|
-
|
|
1183
|
+
/**
|
|
1184
|
+
* Called when `runAction()` catches an unhandled exception.
|
|
1185
|
+
* Override to return a custom human-readable error message for specific
|
|
1186
|
+
* exception types, or to trigger side effects (e.g. alert notifications).
|
|
1187
|
+
*
|
|
1188
|
+
* Return an empty string or null to let the default error handling apply.
|
|
1189
|
+
* The caller's `onException` hook (passed to runAction) is called after this.
|
|
1190
|
+
*/
|
|
1191
|
+
async onException(_params, _opt) {
|
|
601
1192
|
return '';
|
|
602
1193
|
}
|
|
603
1194
|
/**
|
|
604
|
-
* Returns JWT secret and
|
|
605
|
-
*
|
|
606
|
-
*
|
|
1195
|
+
* Returns the JWT secret and verification settings for the current request.
|
|
1196
|
+
* Called by `authenticate()` to resolve auth config per space/tenant.
|
|
1197
|
+
*
|
|
1198
|
+
* Override to implement per-space token secrets, custom algorithms,
|
|
1199
|
+
* or audience/issuer values derived from the request context.
|
|
1200
|
+
*
|
|
1201
|
+
* @param _params The args object passed to the action being authenticated
|
|
607
1202
|
*/
|
|
608
|
-
async getJwtTokenSecretAndSettings(
|
|
1203
|
+
async getJwtTokenSecretAndSettings(_params) {
|
|
609
1204
|
const { space } = this.getContext();
|
|
610
1205
|
return {
|
|
611
1206
|
jwtSecret: space?.tokenSecret || this.config.jwtSecret || '',
|
|
612
1207
|
verifyTokenArgs: this.config.verifyTokenArgs,
|
|
613
1208
|
};
|
|
614
1209
|
}
|
|
1210
|
+
/**
|
|
1211
|
+
* Resolves the current space from context or via the spaceGw gateway.
|
|
1212
|
+
*
|
|
1213
|
+
* Returns `[true, space]` on success, `[false, errorMessage]` on failure.
|
|
1214
|
+
*
|
|
1215
|
+
* Resolution order:
|
|
1216
|
+
* 1. If `context.space` is already populated, return it immediately
|
|
1217
|
+
* (avoids a redundant DB lookup on subsequent calls within the same request)
|
|
1218
|
+
* 2. If `spaceGw` is configured, look up the space by `context.spaceId`
|
|
1219
|
+
* 3. If no `spaceGw` is configured, return `[true, null]` —
|
|
1220
|
+
* callers must handle the null space case
|
|
1221
|
+
*
|
|
1222
|
+
* Side effect: on successful lookup, `context.space` is populated for
|
|
1223
|
+
* future calls within the same request.
|
|
1224
|
+
*/
|
|
615
1225
|
async findSpace() {
|
|
616
1226
|
const { context } = this.config;
|
|
617
1227
|
if (context.space) {
|
|
@@ -622,7 +1232,6 @@ class BaseCore {
|
|
|
622
1232
|
if (!context.spaceId) {
|
|
623
1233
|
return [false, 'Space not specified'];
|
|
624
1234
|
}
|
|
625
|
-
// Lookup space in case we have gateway
|
|
626
1235
|
space = await context.spaceGw.get(context.spaceId || '');
|
|
627
1236
|
if (!space) {
|
|
628
1237
|
return [false, 'Space not found'];
|
|
@@ -631,17 +1240,55 @@ class BaseCore {
|
|
|
631
1240
|
}
|
|
632
1241
|
return [true, space];
|
|
633
1242
|
}
|
|
1243
|
+
/**
|
|
1244
|
+
* Extracts the authentication token and fingerprint from the request.
|
|
1245
|
+
* Called by `authenticate()` before token verification.
|
|
1246
|
+
*
|
|
1247
|
+
* Token resolution order:
|
|
1248
|
+
* 1. Cookie named `space.cookieName`
|
|
1249
|
+
* 2. Authorization header
|
|
1250
|
+
* 3. `authorization` from context (passed explicitly, e.g. from API gateway)
|
|
1251
|
+
*
|
|
1252
|
+
* Fingerprint resolution order:
|
|
1253
|
+
* 1. Cookie named `space.fingerprintCookieName`
|
|
1254
|
+
* 2. X-Fingerprint header
|
|
1255
|
+
* 3. `args.fingerprint` passed to the function
|
|
1256
|
+
*
|
|
1257
|
+
* Override to support additional token sources (e.g. query string tokens
|
|
1258
|
+
* for WebSocket connections, or custom header schemes).
|
|
1259
|
+
*/
|
|
634
1260
|
async extractCredentials(args) {
|
|
635
1261
|
const { req, space, authorization } = args;
|
|
636
1262
|
const token = req.cookies?.[space.cookieName] || req.headers?.[HEADERS.AUTHORIZATION] || authorization;
|
|
637
1263
|
const fingerprint = req.cookies?.[space.fingerprintCookieName] || req.headers?.[HEADERS.FINGERPRINT] || args.fingerprint || '';
|
|
638
|
-
return {
|
|
639
|
-
token,
|
|
640
|
-
fingerprint,
|
|
641
|
-
};
|
|
1264
|
+
return { token, fingerprint };
|
|
642
1265
|
}
|
|
643
|
-
|
|
644
|
-
|
|
1266
|
+
/**
|
|
1267
|
+
* Authenticates the current request.
|
|
1268
|
+
* Called by `runAction()` when `doAuth` is true.
|
|
1269
|
+
*
|
|
1270
|
+
* Returns `[true, '']` on success, `[false, errorMessage]` on failure.
|
|
1271
|
+
*
|
|
1272
|
+
* Authentication flow:
|
|
1273
|
+
* 1. Resolve the current space via `findSpace()`
|
|
1274
|
+
* 2. Extract token + fingerprint via `extractCredentials()`
|
|
1275
|
+
* 3. Resolve JWT secret via `getJwtTokenSecretAndSettings()`
|
|
1276
|
+
* 4. If a token and secret are present, verify the JWT:
|
|
1277
|
+
* - On success: populate context with accountId, roleId, userId,
|
|
1278
|
+
* isSuperAdmin, spaceId, lang from token payload
|
|
1279
|
+
* - On failure: return the verification error
|
|
1280
|
+
* 5. If no token was present, fall back to API key auth:
|
|
1281
|
+
* - Interservice API key (config.interserviceApiKey) for service-to-service calls
|
|
1282
|
+
* - Space API key (space.apiKey) for public API access
|
|
1283
|
+
* - If neither matches: return 'No authentication provided'
|
|
1284
|
+
*
|
|
1285
|
+
* Note: context.spaceId is only set from the token if not already present
|
|
1286
|
+
* in context (header value takes precedence). context.lang defaults to
|
|
1287
|
+
* empty string if neither requestedLang nor tokenData.lang is available.
|
|
1288
|
+
*
|
|
1289
|
+
* Override to add MFA checks, session validation, or custom token formats.
|
|
1290
|
+
*/
|
|
1291
|
+
async authenticate(params, _opt) {
|
|
645
1292
|
const context = this.getContext();
|
|
646
1293
|
const { req, authorization } = context;
|
|
647
1294
|
let authByToken = false;
|
|
@@ -672,13 +1319,17 @@ class BaseCore {
|
|
|
672
1319
|
context.accountId = tokenData.accountId;
|
|
673
1320
|
context.roleId = tokenData.roleId;
|
|
674
1321
|
context.userId = tokenData.userId;
|
|
1322
|
+
// TODO: update the isSuperAdmin
|
|
675
1323
|
context.isSuperAdmin = context.roleId === 'superadmin';
|
|
676
|
-
|
|
677
|
-
context.
|
|
1324
|
+
// Header spaceId takes precedence over token spaceId
|
|
1325
|
+
context.spaceId = context.spaceId || tokenData.spaceId || '';
|
|
1326
|
+
// requestedLang (from Accept-Language header) takes precedence over token lang
|
|
1327
|
+
context.lang = context.requestedLang || tokenData.lang || '';
|
|
678
1328
|
authByToken = true;
|
|
679
1329
|
}
|
|
680
1330
|
if (!authByToken) {
|
|
681
1331
|
if (this.config.interserviceApiKey && context.apiKey === this.config.interserviceApiKey) {
|
|
1332
|
+
// Interservice call — trusted API key for service-to-service communication
|
|
682
1333
|
return [true, ''];
|
|
683
1334
|
}
|
|
684
1335
|
else if (space?.apiKey && space?.apiKey !== context.apiKey) {
|
|
@@ -688,16 +1339,37 @@ class BaseCore {
|
|
|
688
1339
|
}
|
|
689
1340
|
return [true, ''];
|
|
690
1341
|
}
|
|
1342
|
+
/**
|
|
1343
|
+
* Strips the removal suffix from a soft-deleted record's id.
|
|
1344
|
+
*
|
|
1345
|
+
* When a record is soft-deleted with `hasLang`, the gateway appends
|
|
1346
|
+
* a timestamp to the id (e.g. "my-slug_en-20240101T120000+0000") to free
|
|
1347
|
+
* the original key for re-use. This method extracts the original id
|
|
1348
|
+
* by splitting at '~'.
|
|
1349
|
+
*/
|
|
691
1350
|
processRemovedRecord(record) {
|
|
692
1351
|
if (record && typeof record.id === 'string') {
|
|
693
1352
|
record.id = record.id.split('~')[0];
|
|
694
1353
|
}
|
|
695
1354
|
return record;
|
|
696
1355
|
}
|
|
1356
|
+
/**
|
|
1357
|
+
* Builds a partial update object that appends a removal suffix to the
|
|
1358
|
+
* specified fields using a raw DB expression.
|
|
1359
|
+
*
|
|
1360
|
+
* Used to "tombstone" unique fields (slugs, emails, etc.) when soft-deleting,
|
|
1361
|
+
* freeing them for re-use on new records. The suffix includes a UUID to
|
|
1362
|
+
* ensure uniqueness even if the same record is deleted multiple times.
|
|
1363
|
+
*
|
|
1364
|
+
* Example: `{ slug: db.raw("slug || '~removed~' || uuid_generate_v4()") }`
|
|
1365
|
+
*
|
|
1366
|
+
* @param fields A single field name or array of field names to tombstone
|
|
1367
|
+
*/
|
|
697
1368
|
addRemovedModifierToFields(fields) {
|
|
698
1369
|
const obj = {};
|
|
699
1370
|
if (!fields) {
|
|
700
|
-
this.logger.warn(`The 'addRemovedModifierToFields' method expected its fields parameter to be a field name
|
|
1371
|
+
this.logger.warn(`The 'addRemovedModifierToFields' method expected its fields parameter to be a field name ` +
|
|
1372
|
+
`or an array of table field names but got:`, fields);
|
|
701
1373
|
return obj;
|
|
702
1374
|
}
|
|
703
1375
|
castArray(fields).forEach((field) => {
|
|
@@ -705,18 +1377,40 @@ class BaseCore {
|
|
|
705
1377
|
});
|
|
706
1378
|
return obj;
|
|
707
1379
|
}
|
|
1380
|
+
/**
|
|
1381
|
+
* Calculates and sets the next `orderNo` value on `params` before a create.
|
|
1382
|
+
* Called by `create()` when `config.hasOrderNo` is true.
|
|
1383
|
+
*
|
|
1384
|
+
* Queries the gateway for the last record (sorted by orderNo DESC, limit 1)
|
|
1385
|
+
* using the provided filter, then increments by `DEFAULT_ORDER_NO_STEP`.
|
|
1386
|
+
*
|
|
1387
|
+
* Supports two ordering strategies via `config.orderNoAsDecimal`:
|
|
1388
|
+
* - `true` — numeric ordering (e.g. 10, 20, 30)
|
|
1389
|
+
* - `false` — lexicographic string ordering via StrOrderHelpers
|
|
1390
|
+
* (e.g. "a", "b", "c" — useful for reordering without renumbering)
|
|
1391
|
+
*
|
|
1392
|
+
* Does nothing if `params.orderNo` is already set (non-null).
|
|
1393
|
+
*
|
|
1394
|
+
* Fix: changed `!params.orderNo` to `params.orderNo == null` to correctly
|
|
1395
|
+
* handle the case where `orderNo` is explicitly set to `0`.
|
|
1396
|
+
*
|
|
1397
|
+
* @param args.params The params object to mutate with the orderNo value
|
|
1398
|
+
* @param args.filter Filter to scope the orderNo sequence (e.g. by parentId)
|
|
1399
|
+
* @param args.gateway Gateway instance to query for the current max orderNo
|
|
1400
|
+
*/
|
|
708
1401
|
async setOrderNo(args) {
|
|
709
1402
|
const { params, filter, gateway } = args || {};
|
|
710
1403
|
if (typeof params !== 'object') {
|
|
711
|
-
throw new Error(`The 'setOrderNo' expected the parameter to have 'params' object but got: ${JSON.stringify(params)}
|
|
1404
|
+
throw new Error(`The 'setOrderNo' expected the parameter to have 'params' object but got: ${JSON.stringify(params)}`);
|
|
712
1405
|
}
|
|
713
1406
|
if (typeof gateway !== 'object') {
|
|
714
|
-
throw new Error(`The 'setOrderNo' expected the parameter to have 'gateway' object but got: ${JSON.stringify(gateway)}
|
|
1407
|
+
throw new Error(`The 'setOrderNo' expected the parameter to have 'gateway' object but got: ${JSON.stringify(gateway)}`);
|
|
715
1408
|
}
|
|
716
1409
|
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)}
|
|
1410
|
+
throw new Error(`The 'setOrderNo' expected the 'gateway' object to have 'list' method but got: ${JSON.stringify(gateway.list)}`);
|
|
718
1411
|
}
|
|
719
|
-
|
|
1412
|
+
// Fix: use == null instead of falsy check so orderNo: 0 is not overwritten
|
|
1413
|
+
if (params.orderNo == null) {
|
|
720
1414
|
const lastRecord = await gateway.list({
|
|
721
1415
|
filter,
|
|
722
1416
|
params: {
|
|
@@ -728,7 +1422,7 @@ class BaseCore {
|
|
|
728
1422
|
if (this.config.orderNoAsDecimal === true) {
|
|
729
1423
|
params.orderNo =
|
|
730
1424
|
lastRecord[0]?.orderNo != null
|
|
731
|
-
? Number(lastRecord[0]
|
|
1425
|
+
? Number(lastRecord[0].orderNo) + Number(DEFAULT_ORDER_NO_STEP)
|
|
732
1426
|
: Number(DEFAULT_ORDER_NO);
|
|
733
1427
|
}
|
|
734
1428
|
else {
|