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