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