@sdflc/backend-helpers 1.0.111 → 1.0.113

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/README.md +1422 -146
  2. package/build/BaseController.d.ts +20 -0
  3. package/build/BaseController.js +64 -0
  4. package/build/BaseCore.d.ts +470 -33
  5. package/build/BaseCore.js +613 -126
  6. package/build/BaseExternalApiGateway.d.ts +16 -0
  7. package/build/BaseExternalApiGateway.js +54 -0
  8. package/build/BaseGateway.d.ts +455 -17
  9. package/build/BaseGateway.js +502 -56
  10. package/build/BaseRestApiCrudController.d.ts +37 -0
  11. package/build/BaseRestApiCrudController.js +134 -0
  12. package/build/DataCache.d.ts +116 -5
  13. package/build/DataCache.js +144 -22
  14. package/build/Database.d.ts +165 -4
  15. package/build/Database.js +224 -51
  16. package/build/DbMigratorAndSeeder.d.ts +127 -26
  17. package/build/DbMigratorAndSeeder.js +180 -69
  18. package/build/RedisDataLoader.d.ts +144 -21
  19. package/build/RedisDataLoader.js +178 -49
  20. package/build/apiContext.d.ts +0 -8
  21. package/build/apiContext.js +12 -27
  22. package/build/checkItHelpers.d.ts +32 -0
  23. package/build/checkItHelpers.js +73 -7
  24. package/build/commonValidators.d.ts +107 -16
  25. package/build/commonValidators.js +211 -106
  26. package/build/configBuilder.d.ts +23 -0
  27. package/build/configBuilder.js +73 -0
  28. package/build/constants.d.ts +134 -17
  29. package/build/constants.js +95 -15
  30. package/build/dbHelpers.d.ts +89 -29
  31. package/build/dbHelpers.js +175 -86
  32. package/build/dbSeeder.d.ts +10 -1
  33. package/build/dbSeeder.js +80 -15
  34. package/build/dbTableHelpers.d.ts +122 -5
  35. package/build/dbTableHelpers.js +151 -13
  36. package/build/downloadHelpers.d.ts +24 -1
  37. package/build/downloadHelpers.js +51 -21
  38. package/build/esm/BaseController.d.ts +20 -0
  39. package/build/esm/BaseController.js +58 -0
  40. package/build/esm/BaseCore.d.ts +470 -33
  41. package/build/esm/BaseCore.js +615 -128
  42. package/build/esm/BaseExternalApiGateway.d.ts +16 -0
  43. package/build/esm/BaseExternalApiGateway.js +48 -0
  44. package/build/esm/BaseGateway.d.ts +455 -17
  45. package/build/esm/BaseGateway.js +503 -57
  46. package/build/esm/BaseRestApiCrudController.d.ts +37 -0
  47. package/build/esm/BaseRestApiCrudController.js +131 -0
  48. package/build/esm/DataCache.d.ts +116 -5
  49. package/build/esm/DataCache.js +142 -20
  50. package/build/esm/Database.d.ts +165 -4
  51. package/build/esm/Database.js +224 -51
  52. package/build/esm/DbMigratorAndSeeder.d.ts +127 -26
  53. package/build/esm/DbMigratorAndSeeder.js +184 -71
  54. package/build/esm/RedisDataLoader.d.ts +144 -21
  55. package/build/esm/RedisDataLoader.js +179 -50
  56. package/build/esm/apiContext.d.ts +0 -8
  57. package/build/esm/apiContext.js +12 -27
  58. package/build/esm/checkItHelpers.d.ts +32 -0
  59. package/build/esm/checkItHelpers.js +73 -7
  60. package/build/esm/commonValidators.d.ts +107 -16
  61. package/build/esm/commonValidators.js +209 -105
  62. package/build/esm/configBuilder.d.ts +23 -0
  63. package/build/esm/configBuilder.js +69 -0
  64. package/build/esm/constants.d.ts +134 -17
  65. package/build/esm/constants.js +94 -14
  66. package/build/esm/dbHelpers.d.ts +89 -29
  67. package/build/esm/dbHelpers.js +171 -81
  68. package/build/esm/dbSeeder.d.ts +10 -1
  69. package/build/esm/dbSeeder.js +81 -16
  70. package/build/esm/dbTableHelpers.d.ts +122 -5
  71. package/build/esm/dbTableHelpers.js +152 -14
  72. package/build/esm/downloadHelpers.d.ts +24 -1
  73. package/build/esm/downloadHelpers.js +51 -21
  74. package/build/esm/index.d.ts +5 -2
  75. package/build/esm/index.js +5 -2
  76. package/build/esm/interfaces/ApiContext.d.ts +7 -3
  77. package/build/esm/interfaces/ApiContextInterface.d.ts +1 -1
  78. package/build/esm/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  79. package/build/esm/interfaces/BaseControllerPropsInterface.js +1 -0
  80. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  81. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  82. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +87 -9
  83. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  84. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  85. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.js +2 -0
  86. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  87. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  88. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  89. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.js +2 -0
  90. package/build/esm/interfaces/BuildConfigOptions.d.ts +18 -0
  91. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  92. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  93. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  94. package/build/esm/interfaces/CacheInterface.d.ts +18 -1
  95. package/build/esm/interfaces/CacheInterface.js +1 -0
  96. package/build/esm/interfaces/CoreActionInterface.d.ts +20 -0
  97. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +38 -4
  98. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  99. package/build/esm/interfaces/DataCachePropsInterface.d.ts +21 -0
  100. package/build/esm/interfaces/DataCachePropsInterface.js +2 -0
  101. package/build/esm/interfaces/DatabaseOptions.d.ts +24 -10
  102. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  103. package/build/esm/interfaces/DatabaseReadInterface.d.ts +58 -3
  104. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  105. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  106. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  107. package/build/esm/interfaces/DownloadFileArgs.d.ts +21 -2
  108. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  109. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  110. package/build/esm/interfaces/ListArgsInterface.d.ts +18 -0
  111. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  112. package/build/esm/interfaces/LoaderInterface.d.ts +36 -1
  113. package/build/esm/interfaces/LoaderInterface.js +1 -0
  114. package/build/esm/interfaces/UserTokenParams.d.ts +23 -5
  115. package/build/esm/interfaces/UserTokenParams.js +1 -0
  116. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  117. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  118. package/build/esm/interfaces/index.d.ts +4 -0
  119. package/build/esm/interfaces/index.js +4 -0
  120. package/build/esm/knexConfigBuilder.d.ts +25 -0
  121. package/build/esm/knexConfigBuilder.js +100 -36
  122. package/build/esm/parseIds.d.ts +6 -0
  123. package/build/esm/parseIds.js +13 -0
  124. package/build/esm/passwordHelpers.d.ts +22 -0
  125. package/build/esm/passwordHelpers.js +40 -8
  126. package/build/esm/redisClient.d.ts +57 -4
  127. package/build/esm/redisClient.js +40 -54
  128. package/build/esm/resolveClientIp.d.ts +15 -0
  129. package/build/esm/resolveClientIp.js +34 -0
  130. package/build/esm/resolversHelpers.d.ts +21 -1
  131. package/build/esm/resolversHelpers.js +48 -26
  132. package/build/esm/userToken.d.ts +50 -1
  133. package/build/esm/userToken.js +85 -20
  134. package/build/esm/utils.d.ts +20 -0
  135. package/build/esm/utils.js +23 -1
  136. package/build/index.d.ts +5 -2
  137. package/build/index.js +5 -2
  138. package/build/interfaces/ApiContext.d.ts +7 -3
  139. package/build/interfaces/ApiContextInterface.d.ts +1 -1
  140. package/build/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  141. package/build/interfaces/BaseControllerPropsInterface.js +2 -0
  142. package/build/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  143. package/build/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  144. package/build/interfaces/BaseCorePropsInterface.d.ts +87 -9
  145. package/build/interfaces/BaseCorePropsInterface.js +1 -0
  146. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  147. package/build/interfaces/BaseExternalApiGatewayPropsInterface.js +3 -0
  148. package/build/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  149. package/build/interfaces/BaseGatewayPropsInterface.js +1 -0
  150. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  151. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.js +3 -0
  152. package/build/interfaces/BuildConfigOptions.d.ts +18 -0
  153. package/build/interfaces/BuildConfigOptions.js +1 -0
  154. package/build/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  155. package/build/interfaces/BuildListQueryArgsInterface.js +1 -0
  156. package/build/interfaces/CacheInterface.d.ts +18 -1
  157. package/build/interfaces/CacheInterface.js +1 -0
  158. package/build/interfaces/CoreActionInterface.d.ts +20 -0
  159. package/build/interfaces/CreateUserTokenArgs.d.ts +38 -4
  160. package/build/interfaces/CreateUserTokenArgs.js +1 -0
  161. package/build/interfaces/DataCachePropsInterface.d.ts +21 -0
  162. package/build/interfaces/DataCachePropsInterface.js +3 -0
  163. package/build/interfaces/DatabaseOptions.d.ts +24 -10
  164. package/build/interfaces/DatabaseOptions.js +1 -0
  165. package/build/interfaces/DatabaseReadInterface.d.ts +58 -3
  166. package/build/interfaces/DatabaseReadInterface.js +1 -0
  167. package/build/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  168. package/build/interfaces/DbFieldAddDefaultInterface.js +1 -0
  169. package/build/interfaces/DownloadFileArgs.d.ts +21 -2
  170. package/build/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  171. package/build/interfaces/ExtractCredentialsArgs.js +1 -0
  172. package/build/interfaces/ListArgsInterface.d.ts +18 -0
  173. package/build/interfaces/ListArgsInterface.js +1 -0
  174. package/build/interfaces/LoaderInterface.d.ts +36 -1
  175. package/build/interfaces/LoaderInterface.js +1 -0
  176. package/build/interfaces/UserTokenParams.d.ts +23 -5
  177. package/build/interfaces/UserTokenParams.js +1 -0
  178. package/build/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  179. package/build/interfaces/VerifyUserTokenArgs.js +1 -0
  180. package/build/interfaces/index.d.ts +4 -0
  181. package/build/interfaces/index.js +4 -0
  182. package/build/knexConfigBuilder.d.ts +25 -0
  183. package/build/knexConfigBuilder.js +99 -35
  184. package/build/parseIds.d.ts +6 -0
  185. package/build/parseIds.js +17 -0
  186. package/build/passwordHelpers.d.ts +22 -0
  187. package/build/passwordHelpers.js +40 -8
  188. package/build/redisClient.d.ts +57 -4
  189. package/build/redisClient.js +40 -54
  190. package/build/resolveClientIp.d.ts +15 -0
  191. package/build/resolveClientIp.js +38 -0
  192. package/build/resolversHelpers.d.ts +21 -1
  193. package/build/resolversHelpers.js +48 -26
  194. package/build/userToken.d.ts +50 -1
  195. package/build/userToken.js +85 -20
  196. package/build/utils.d.ts +20 -0
  197. package/build/utils.js +23 -1
  198. package/package.json +19 -18
  199. package/build/baseController.d.ts +0 -17
  200. package/build/baseController.js +0 -63
  201. package/build/configBulder.d.ts +0 -2
  202. package/build/configBulder.js +0 -36
  203. package/build/esm/baseController.d.ts +0 -17
  204. package/build/esm/baseController.js +0 -57
  205. package/build/esm/configBulder.d.ts +0 -2
  206. package/build/esm/configBulder.js +0 -32
@@ -0,0 +1,16 @@
1
+ import { Logger } from '@sdflc/utils';
2
+ import { BaseExternalApiGatewayPropsInterface } from './interfaces';
3
+ declare abstract class BaseExternalApiGateway {
4
+ protected logger: Logger;
5
+ protected baseUrl: string;
6
+ protected timeoutMs: number;
7
+ private _credentials;
8
+ private _credentialsSet;
9
+ constructor(props?: BaseExternalApiGatewayPropsInterface);
10
+ setCredentials(credentials: string | Record<string, any>): this;
11
+ hasCredentials(): boolean;
12
+ protected get credentials(): string | Record<string, any>;
13
+ protected assertCredentials(): void;
14
+ protected onCredentialsSet(): void;
15
+ }
16
+ export { BaseExternalApiGateway };
@@ -0,0 +1,48 @@
1
+ // ./src/baseExternalApiGateway.ts
2
+ import check from 'check-types';
3
+ import { Logger, LoggerLevels, isLogger } from '@sdflc/utils';
4
+ class BaseExternalApiGateway {
5
+ logger;
6
+ baseUrl;
7
+ timeoutMs;
8
+ _credentials = null;
9
+ _credentialsSet = false;
10
+ constructor(props) {
11
+ const { credentials, baseUrl, timeoutMs, logger } = props || {};
12
+ this.baseUrl = baseUrl ?? '';
13
+ this.timeoutMs = timeoutMs ?? 10_000;
14
+ this.logger = isLogger(logger) ? logger : new Logger({ level: LoggerLevels.ERROR });
15
+ if (credentials !== undefined) {
16
+ this.setCredentials(credentials);
17
+ }
18
+ }
19
+ // ─── Credentials ───────────────────────────────────────────────────────────
20
+ setCredentials(credentials) {
21
+ if (!check.string(credentials) && !check.object(credentials)) {
22
+ throw new Error(`${this.constructor.name}.setCredentials: credentials must be a string or an object`);
23
+ }
24
+ if (check.string(credentials) && !credentials.trim()) {
25
+ throw new Error(`${this.constructor.name}.setCredentials: credentials string must not be empty`);
26
+ }
27
+ this._credentials = credentials;
28
+ this._credentialsSet = true;
29
+ this.onCredentialsSet();
30
+ return this;
31
+ }
32
+ hasCredentials() {
33
+ return this._credentialsSet;
34
+ }
35
+ get credentials() {
36
+ return this._credentials;
37
+ }
38
+ assertCredentials() {
39
+ if (!this._credentialsSet) {
40
+ throw new Error(`${this.constructor.name}: credentials have not been set. ` + `Call setCredentials() before making API calls.`);
41
+ }
42
+ }
43
+ // ─── Lifecycle hook ────────────────────────────────────────────────────────
44
+ onCredentialsSet() {
45
+ // no-op — override in subclass to initialise SDK clients etc.
46
+ }
47
+ }
48
+ export { BaseExternalApiGateway };
@@ -2,55 +2,493 @@ import { DateTimeHelpers, Logger } from '@sdflc/utils';
2
2
  import { DataCache } from './DataCache';
3
3
  import { ApiContext, BaseGatewayPropsInterface, BuildListQueryArgsInterface, CacheInterface, ListArgsInterface, LoaderInterface } from './interfaces';
4
4
  import { Database } from './Database';
5
+ /**
6
+ * BaseGateway is the foundation for all database-backed gateway classes.
7
+ *
8
+ * A gateway is a low-level data-access object responsible for a single
9
+ * database table. It handles CRUD operations, cache management, soft-delete
10
+ * patterns, field transforms, and query filtering.
11
+ *
12
+ * Gateways are instantiated per-request — they receive a full ApiContext
13
+ * (including db, spaceId, userId etc.) at construction time and must not
14
+ * be reused across requests. This is critical because `dateTimeNow` and all
15
+ * context-derived values (userId, spaceId) are snapshotted at construction.
16
+ *
17
+ * Subclasses typically override:
18
+ * - `onListFilter()` — to add resource-specific WHERE clauses
19
+ * - `onUpdateFilter()` — to add resource-specific update conditions
20
+ * - `onRemoveFilter()` — to add resource-specific remove conditions
21
+ * - `transformOnOut()` — to shape outbound records (e.g. rename fields,
22
+ * attach computed properties)
23
+ * - `generateId()` — to use a domain-specific ID strategy
24
+ *
25
+ * The loader (DataCache by default) is used for batched per-id loading
26
+ * via DataLoader semantics. It is bypassed when `noCache: true` is set in
27
+ * config, or when `list()` is called with `useCache: false`.
28
+ */
5
29
  declare class BaseGateway {
6
30
  protected config: BaseGatewayPropsInterface;
7
31
  protected logger: Logger;
8
32
  protected loader: LoaderInterface | DataCache;
9
33
  protected dateTime: DateTimeHelpers;
34
+ /**
35
+ * Timestamp captured at construction time. Used as the value for
36
+ * createdAt / updatedAt / removedAt fields so that all writes within
37
+ * a single request share the same timestamp.
38
+ *
39
+ * IMPORTANT: This is set once at instantiation — gateways must be
40
+ * created per-request. Reusing a gateway instance across requests will
41
+ * result in stale timestamps being written to the database.
42
+ */
10
43
  protected dateTimeNow: Date;
11
44
  constructor(props: BaseGatewayPropsInterface);
45
+ /**
46
+ * Returns the full gateway config object.
47
+ * Useful for subclasses or external code that needs to inspect configuration
48
+ * without accessing protected fields directly.
49
+ */
12
50
  getConfig(): BaseGatewayPropsInterface;
51
+ /**
52
+ * Merges the provided props into the existing config.
53
+ * Allows runtime config changes (e.g. swapping the table, adjusting chunk size)
54
+ * without recreating the gateway.
55
+ *
56
+ * Returns `this` for chaining.
57
+ */
13
58
  setConfigPart(props: BaseGatewayPropsInterface): this;
59
+ /**
60
+ * Replaces the loader used for `get()` and `getMany()` calls.
61
+ * The loader must implement the `LoaderInterface` (i.e. `load` and `loadMany`).
62
+ *
63
+ * Use this to inject a custom DataLoader, a mock in tests, or a loader
64
+ * backed by a different cache layer (Redis, etc.).
65
+ *
66
+ * Returns `this` for chaining.
67
+ */
14
68
  setLoader(loader: LoaderInterface): this;
69
+ /**
70
+ * Replaces the loader with a new DataCache instance built from the
71
+ * provided cache config merged with the existing gateway config.
72
+ *
73
+ * Use this when you want to adjust caching behaviour (TTL, batch size, etc.)
74
+ * without providing a fully custom loader.
75
+ *
76
+ * Returns `this` for chaining.
77
+ */
15
78
  setLoaderConfig(config: CacheInterface): this;
16
79
  /**
17
- * Generates object's ID
18
- * @param object use them when overriding the generate method and you may need data from an object
19
- * @returns unique ID, by default it is UUID v4
80
+ * Generates a unique ID for a new record.
81
+ *
82
+ * Defaults to UUID v4. Override in a subclass to use a different ID
83
+ * strategy (e.g. nanoid, sequential IDs, composite keys).
84
+ *
85
+ * The `object` parameter is the record about to be inserted — it is
86
+ * available in case the ID needs to be derived from the object's data.
87
+ */
88
+ generateId(_object?: any): Promise<string>;
89
+ /**
90
+ * Applies WHERE clauses to a list query based on the provided filter params.
91
+ * Called internally by `list()` after the base query is built.
92
+ *
93
+ * Override in subclasses to add resource-specific filters. Always call
94
+ * `super.onListFilter(query, filterParams)` first to preserve the standard
95
+ * filtering behaviour (status, spaceId, lang, keyword, etc.).
96
+ *
97
+ * Built-in filter behaviours (each controlled by a config flag):
98
+ * - `hasStatus` — filters by status; defaults to activeStatuses if
99
+ * no status param is provided
100
+ * - `hasRemovedAt` — excludes soft-deleted records (removedAt IS NULL)
101
+ * - `hasSpace` — scopes to the current spaceId from context or params
102
+ * - `hasLang` — filters by language
103
+ * - `fieldForKeyword` — applies a case-insensitive LIKE on the configured field
104
+ * - `filterByUserField` — scopes to the current userId from context
105
+ *
106
+ * Nuance: `hasSpace` checks both `filterParams[SPACE_ID]` and
107
+ * `context.spaceId`, preferring the explicit param. If neither is set and
108
+ * `hasSpace` is true, the filter is skipped entirely — no space scoping.
20
109
  */
21
- generateId(object?: any): Promise<string>;
22
110
  onListFilter(query: any, filterParams: any): Promise<void>;
111
+ /**
112
+ * Applies WHERE clauses to an update query based on the provided filter params.
113
+ * Called internally by `update()` after the UPDATE statement is prepared.
114
+ *
115
+ * Returns the number of filter conditions applied. If this is 0, `update()`
116
+ * will throw to prevent an unfiltered UPDATE from affecting all rows.
117
+ *
118
+ * Override in subclasses to add resource-specific update conditions.
119
+ * Always call `super.onUpdateFilter()` first.
120
+ *
121
+ * Built-in filter behaviours:
122
+ * - Always filters by the id field (idFieldUpdateRemove) when present
123
+ * - `hasVersion` — adds an optimistic-lock check on the version field,
124
+ * preventing updates if the version has changed since the record was read
125
+ * - `hasStatus` — excludes already-removed records from being updated
126
+ */
23
127
  onUpdateFilter(query: any, filterParams: any): Promise<number>;
128
+ /**
129
+ * Applies WHERE clauses to a remove query based on the provided filter params.
130
+ * Called internally by `remove()` after the DELETE/UPDATE statement is prepared.
131
+ *
132
+ * Returns the number of filter conditions applied. If this is 0, `remove()`
133
+ * will throw to prevent an unfiltered DELETE or soft-delete UPDATE.
134
+ *
135
+ * `filterParams` can be a single object or an array of objects. The method
136
+ * collects the id field value from each entry and applies a single whereIn.
137
+ *
138
+ * Override in subclasses to add resource-specific remove conditions.
139
+ * Always call `super.onRemoveFilter()` first.
140
+ *
141
+ * Built-in filter behaviours:
142
+ * - Collects the id field (idFieldUpdateRemove) from each item in filterParams
143
+ * - `hasStatus` — adds a guard to prevent double-removal of already-removed records
144
+ */
24
145
  onRemoveFilter(query: any, filterParams: any): Promise<number>;
146
+ /**
147
+ * Transforms a params object before it is inserted into the database.
148
+ * Called once per object inside the `create()` loop, after the ID is generated.
149
+ *
150
+ * Mutates and returns the params object. Override in subclasses to add
151
+ * computed fields, enforce defaults, or validate data before insert.
152
+ * Always call `super.transformOnCreate(params)` first.
153
+ *
154
+ * Built-in transformations (each controlled by a config flag):
155
+ * - `hasCreatedAt` — sets createdAt to the gateway's construction timestamp
156
+ * - `hasCreatedBy` — sets createdBy to context.userId if not already set
157
+ * - `hasUserId` — sets userId to context.userId if not already set
158
+ * - `hasSpace` — sets spaceId from context (always overwritten)
159
+ * - `hasVersion` — initialises version to 0
160
+ * - `hasLang` + `localizationForField` — builds a composite id from the
161
+ * localisation field value and the lang field (e.g. "slug_en")
162
+ *
163
+ * Nuance: createdBy and userId are only set if not already present in params,
164
+ * allowing the caller to supply an explicit value (e.g. when migrating data).
165
+ * spaceId, by contrast, is always overwritten from context to prevent spoofing.
166
+ */
25
167
  transformOnCreate(params: any): Promise<any>;
168
+ /**
169
+ * Transforms a params object before it is applied as an UPDATE in the database.
170
+ * Called by `update()`, `increment()`, and `decrement()` before the query runs.
171
+ *
172
+ * Mutates and returns the params object. Override in subclasses to add
173
+ * computed fields or enforce constraints before update.
174
+ * Always call `super.transformOnUpdate(params, where)` first.
175
+ *
176
+ * The `where` parameter carries the filter criteria (including the id) and is
177
+ * available for subclasses that need to derive update values from the filter.
178
+ *
179
+ * Built-in transformations:
180
+ * - `hasUpdatedAt` — sets updatedAt to the gateway's construction timestamp
181
+ * - `hasUpdatedBy` — sets updatedBy to context.userId if not already set
182
+ * - `hasVersion` — increments version by 1 (only if version is present
183
+ * and numeric in params; no-op otherwise)
184
+ * - `hasLang` + `localizationForField` — rebuilds the composite id from the
185
+ * localisation field value and lang (same logic as transformOnCreate)
186
+ *
187
+ * Nuance: version increment only fires if the version is already present in
188
+ * params. This allows callers to explicitly omit version management when needed
189
+ * (e.g. admin operations that should not bump the version).
190
+ */
26
191
  transformOnUpdate(params: any, where?: any): Promise<any>;
192
+ /**
193
+ * Transforms a params object before it is applied as an upsert (INSERT ... ON CONFLICT MERGE).
194
+ * Called by `set()` for each object before the batch is inserted.
195
+ *
196
+ * This is a superset of both `transformOnCreate` and `transformOnUpdate`:
197
+ * it applies creation fields (createdAt, createdBy, spaceId) AND update fields
198
+ * (updatedAt, updatedBy) in a single pass, making it suitable for upserts where
199
+ * you don't know in advance whether the record already exists.
200
+ *
201
+ * Mutates and returns the params object. Override in subclasses as needed.
202
+ * Always call `super.transformOnSet(params)` first.
203
+ *
204
+ * Built-in transformations:
205
+ * - `hasCreatedAt` — sets createdAt (will be skipped in the ON CONFLICT
206
+ * MERGE clause via skipFields — existing records keep
207
+ * their original createdAt)
208
+ * - `hasCreatedBy` — sets createdBy if not already set (also skipped on merge)
209
+ * - `hasUserId` — sets userId if not already set
210
+ * - `hasSpace` — sets spaceId (also skipped on merge)
211
+ * - `hasUpdatedAt` — sets updatedAt (always merged on conflict)
212
+ * - `hasUpdatedBy` — sets updatedBy if not already set
213
+ * - `hasVersion` — increments version if present and numeric,
214
+ * otherwise initialises to 0 (create path)
215
+ * - `hasLang` + `localizationForField` — builds composite id from localisation field + lang
216
+ */
27
217
  transformOnSet(params: any): Promise<any>;
218
+ /**
219
+ * Builds the patch object applied to a record when it is soft-deleted.
220
+ * Called by `remove()` when `hardRemove` is false and `hasRemovedAt` is true.
221
+ *
222
+ * Returns a new object (merged from `args`) with removal fields populated.
223
+ * Override in subclasses to add custom soft-delete fields.
224
+ * Always call `super.transformOnRemove(args)` first.
225
+ *
226
+ * The `args` parameter is the original `where` filter passed to `remove()`.
227
+ * It is available so subclasses can derive removal values from the filter
228
+ * (e.g. storing which id was removed). In the base implementation it is
229
+ * spread into the patch object as-is.
230
+ *
231
+ * Built-in transformations:
232
+ * - `hasRemovedAt` — sets removedAt to the current time (dayjs, not
233
+ * dateTimeNow — removal time is always real-time,
234
+ * not the gateway construction timestamp)
235
+ * - `hasRemovedAtStr` — sets removedAtStr to a formatted string timestamp
236
+ * (YYYYMMDDTHHmmssZ), useful for building composite
237
+ * keys that need to encode the removal time
238
+ * - `hasStatus` — sets status to STATUSES.REMOVED
239
+ * - `hasRemovedBy` — sets removedBy to context.userId if not already set
240
+ * - `hasLang` + `localizationForField` — appends the removal timestamp to
241
+ * the id field using a raw CONCAT expression, so
242
+ * the old localisation key is freed up for re-use
243
+ *
244
+ * Nuance: removedAt uses `dayjs()` (current time) rather than `dateTimeNow`
245
+ * (construction time). This is intentional — removal timestamps should be
246
+ * as accurate as possible and are not batch-grouped like create/update times.
247
+ */
28
248
  transformOnRemove(args?: any): Promise<any>;
249
+ /**
250
+ * Transforms a record after it is read from the database, before it is
251
+ * returned to the caller.
252
+ *
253
+ * The base implementation is a no-op — it returns the item unchanged.
254
+ * Override in subclasses to rename fields, attach computed properties,
255
+ * strip sensitive columns, or convert types (e.g. parse JSON strings).
256
+ *
257
+ * Called by: `list()`, `create()`, `update()`, `updateMany()`,
258
+ * `increment()`, `decrement()`, `set()`, `remove()`.
259
+ *
260
+ * Note: `get()` and `getMany()` go through the loader (DataCache/DataLoader)
261
+ * and do NOT call `transformOnOut()` — transformations on cached records
262
+ * must be handled in the loader's priming logic or in the calling code.
263
+ */
29
264
  protected transformOnOut(item: any): any;
265
+ /**
266
+ * Returns the requestId from the current ApiContext.
267
+ * Useful for correlating log entries or error reports to a specific request.
268
+ */
30
269
  getRequestId(): string;
270
+ /**
271
+ * Returns the full ApiContext associated with this gateway instance.
272
+ * The context carries request-scoped values: userId, spaceId, headers,
273
+ * other gateways, cores, db, etc.
274
+ */
31
275
  getContext(): ApiContext;
32
- getGateways(): any;
276
+ /**
277
+ * Returns all gateway instances from the current request context.
278
+ * Allows one gateway to call another (e.g. UserGateway calling RoleGateway)
279
+ * without going through a core, using the same shared context and db connection.
280
+ *
281
+ * Returns an empty object if context is not available.
282
+ */
283
+ getGateways(): Record<string, any>;
284
+ /**
285
+ * Returns the Database instance from config.
286
+ * All query builders are derived from this instance.
287
+ */
33
288
  getDb(): Database;
289
+ /**
290
+ * Returns a Knex query builder scoped to this gateway's table.
291
+ * The builder is a fresh instance each time — it does not carry state
292
+ * between calls.
293
+ */
34
294
  getBuilder(): any;
295
+ /**
296
+ * Returns the primary key field name used for SELECT and loader operations.
297
+ * Defaults to the global ID_FIELD constant if not set in config.
298
+ *
299
+ * Note: this may differ from `getIdFieldUpdateRemove()` — some tables use
300
+ * a different column for update/delete filtering (e.g. a composite key)
301
+ * while listing and loading still uses the primary key.
302
+ */
35
303
  getIdField(): string;
304
+ /**
305
+ * Returns the field name used to identify records in UPDATE and DELETE
306
+ * WHERE clauses. Falls back through idFieldUpdateRemove → idField → ID_FIELD.
307
+ *
308
+ * Separate from `getIdField()` to support tables where the logical primary
309
+ * key used for loading differs from the column used for writes
310
+ * (e.g. a table with a UUID primary key but a separate "slug" as update target).
311
+ */
36
312
  getIdFieldUpdateRemove(): string;
313
+ /**
314
+ * Loads a single record by id via the loader (DataCache/DataLoader).
315
+ * Leverages DataLoader batching — multiple `get()` calls within the same
316
+ * tick are coalesced into a single database query.
317
+ *
318
+ * Results are cached for the duration of the request. To bypass the cache,
319
+ * call `list()` with `useCache: false` instead.
320
+ */
37
321
  get(id: any): Promise<any>;
38
- getMany(ids: any[]): Promise<any>;
39
- buildListQuery(args?: BuildListQueryArgsInterface): Promise<any>;
40
- list(args?: ListArgsInterface): Promise<any>;
322
+ /**
323
+ * Loads multiple records by their ids via the loader (DataCache/DataLoader).
324
+ * Returns results in the same order as the input ids array, with `null`
325
+ * entries for any ids that were not found (DataLoader semantics).
326
+ *
327
+ * Leverages DataLoader batching — all ids are fetched in a single query.
328
+ * Results are cached for the duration of the request.
329
+ */
330
+ getMany(ids: any[]): Promise<any[]>;
331
+ /**
332
+ * Builds the base SELECT query for `list()`.
333
+ * Override in subclasses to add JOINs, computed columns, or subqueries
334
+ * that should always be present in list results.
335
+ *
336
+ * The `fieldsToUse` argument determines which columns are selected:
337
+ * - When `useCache` is true (default), only the id field is selected —
338
+ * the full records are then fetched via the loader/cache.
339
+ * - When `useCache` is false, `selectFields` from config are used, falling
340
+ * back to '*' if not configured.
341
+ *
342
+ * Returns an object `{ query }` so subclasses can destructure it and
343
+ * attach additional query segments before returning.
344
+ */
345
+ buildListQuery(args?: BuildListQueryArgsInterface): Promise<{
346
+ query: any;
347
+ }>;
348
+ /**
349
+ * Fetches a paginated, filtered list of records from the database.
350
+ *
351
+ * Flow:
352
+ * 1. Builds the base query via `buildListQuery()`
353
+ * 2. Applies filter conditions via `onListFilter()`
354
+ * 3. Applies pagination (limit/offset) and sorting
355
+ * 4. If `useCache` is true, fetches only ids then loads full records
356
+ * via the loader (DataLoader batching + in-memory cache)
357
+ * 5. Transforms each result via `transformOnOut()`
358
+ *
359
+ * Cache behaviour:
360
+ * - `useCache` defaults to `!config.noCache`
361
+ * - When true, the list query selects only id fields, and full records
362
+ * are hydrated through the DataLoader. This means list results benefit
363
+ * from the same cache as `get()` / `getMany()` calls in the same request.
364
+ * - When false, `selectFields` are fetched directly without going through
365
+ * the loader. Use this for aggregations, reports, or large exports.
366
+ *
367
+ * Returns an empty array immediately if `config.table` is not set.
368
+ */
369
+ list(args?: ListArgsInterface): Promise<any[]>;
370
+ /**
371
+ * Inserts one or more records into the database.
372
+ *
373
+ * Accepts a single object or an array of objects (via castArray).
374
+ * For each object:
375
+ * 1. Generates a new id via `generateId()`
376
+ * 2. Applies `transformOnCreate()` to set audit fields, spaceId, version, etc.
377
+ *
378
+ * Inserts are batched into chunks of `config.insertChunkSize` (default 2500)
379
+ * to avoid hitting database parameter limits on large arrays.
380
+ *
381
+ * Returns all inserted records (via RETURNING), each passed through
382
+ * `transformOnOut()`.
383
+ *
384
+ * Note: does NOT prime the loader cache with the newly created records.
385
+ * Subsequent `get()` calls for these ids will hit the database.
386
+ */
41
387
  create(args: any): Promise<any[]>;
42
- update(where: any, params: any): Promise<any>;
388
+ /**
389
+ * Updates one or more records matching the `where` filter.
390
+ *
391
+ * Flow:
392
+ * 1. Applies `transformOnUpdate()` to set audit fields and increment version
393
+ * 2. Builds the UPDATE query with RETURNING
394
+ * 3. Applies WHERE conditions via `onUpdateFilter()`
395
+ * 4. Throws if no filter conditions were applied (safety guard against
396
+ * unfiltered updates that would affect all rows)
397
+ * 5. Clears affected records from the loader cache
398
+ * 6. Returns updated records through `transformOnOut()`
399
+ *
400
+ * The `where` object should contain the id field and optionally version
401
+ * (for optimistic locking). Additional filter logic can be added by
402
+ * overriding `onUpdateFilter()`.
403
+ *
404
+ * Nuance: if `hasVersion` is configured and `where` does not include a
405
+ * version, the version check is skipped. This allows unconditional updates
406
+ * (e.g. admin operations) by simply omitting the version from the filter.
407
+ */
408
+ update(where: any, params: any): Promise<any[]>;
409
+ /**
410
+ * Updates multiple records, each with its own where filter and params.
411
+ *
412
+ * Accepts an array of `{ where, params }` pairs (or a single pair, which
413
+ * is normalised to an array). Each pair is processed sequentially via
414
+ * `update()`, so each item gets its own filter validation, audit field
415
+ * transform, and cache invalidation.
416
+ *
417
+ * Returns all updated records across all pairs, flattened into a single
418
+ * array, each passed through `transformOnOut()`.
419
+ *
420
+ * Note: cache clearing is handled inside each `update()` call — there is
421
+ * no second pass over the results here.
422
+ */
43
423
  updateMany(params: any): Promise<any[]>;
44
- increment(where: any, params: any): Promise<any>;
45
- decrement(where: any, params: any): Promise<any>;
46
424
  /**
47
- * Inserts or updates data in the database.
48
- * If the element of given array has not empty id field then the record is updated
49
- * oterwise inserted
50
- * @param params Array of objects to update or create
51
- * @returns Array of updated or inserted objects
425
+ * Increments numeric field(s) on records matching the `where` filter.
426
+ * Uses the database's native INCREMENT operation rather than a read-modify-write,
427
+ * making it safe for concurrent requests.
428
+ *
429
+ * `params` should be an object mapping field names to the increment amounts
430
+ * (e.g. `{ viewCount: 1 }`). `transformOnUpdate()` is still called, so
431
+ * audit fields (updatedAt, updatedBy) and version are updated as normal.
432
+ *
433
+ * Throws if no filter conditions are applied (same safety guard as `update()`).
434
+ * Clears affected records from the loader cache after the operation.
435
+ */
436
+ increment(where: any, params: any): Promise<any[]>;
437
+ /**
438
+ * Decrements numeric field(s) on records matching the `where` filter.
439
+ * Mirror of `increment()` using the database's native DECREMENT operation.
440
+ *
441
+ * Same behaviour, safety guards, and cache invalidation as `increment()`.
442
+ */
443
+ decrement(where: any, params: any): Promise<any[]>;
444
+ /**
445
+ * Upserts one or more records using INSERT ... ON CONFLICT ... MERGE.
446
+ *
447
+ * For each object:
448
+ * 1. Applies `transformOnSet()` (combined create + update transforms)
449
+ * 2. Generates an id if none is present
450
+ *
451
+ * The merge behaviour:
452
+ * - Conflict target: `config.setFields` if set, otherwise the id field
453
+ * - Fields merged on conflict: all keys found across all objects, minus
454
+ * `skipFields` (createdAt, createdBy, spaceId when their flags are set)
455
+ * - skipFields ensures that on conflict (update path), creation-time
456
+ * fields are not overwritten — existing records keep their original
457
+ * createdAt, createdBy, and spaceId values
458
+ * - If `config.mergeFields` is set, it takes precedence over the
459
+ * auto-derived field list entirely
460
+ *
461
+ * Inserts are batched into chunks of `config.insertChunkSize` (default 2500).
462
+ *
463
+ * Returns all upserted records (via RETURNING), each passed through
464
+ * `transformOnOut()`.
465
+ *
466
+ * Nuance: fields are collected from all objects (not just the first) to
467
+ * avoid silently dropping fields that only appear on some items in the batch.
52
468
  */
53
469
  set(params: any): Promise<any[]>;
54
- remove(where: any): Promise<any>;
470
+ /**
471
+ * Removes records matching the `where` filter, either hard or soft.
472
+ *
473
+ * Hard vs soft delete:
474
+ * - Hard delete (`hardRemove: true` OR `hasRemovedAt: false`):
475
+ * Issues a DELETE query. Records are permanently removed.
476
+ * - Soft delete (default when `hasRemovedAt: true`):
477
+ * Issues an UPDATE with the removal patch from `transformOnRemove()`.
478
+ * Records are retained in the database with removedAt, status = REMOVED,
479
+ * and optionally removedBy set.
480
+ *
481
+ * The `where` parameter is passed to both `onRemoveFilter()` (for the WHERE
482
+ * clause) and `transformOnRemove()` (so the removal patch can reference
483
+ * the filter, e.g. for lang/localisation key rotation).
484
+ *
485
+ * Throws if no filter conditions are applied — a safety guard to prevent
486
+ * an unfiltered DELETE or soft-delete UPDATE from affecting all rows.
487
+ *
488
+ * Clears affected records from the loader cache after the operation.
489
+ * Returns all affected records (via RETURNING), each passed through
490
+ * `transformOnOut()`.
491
+ */
492
+ remove(where: any): Promise<any[]>;
55
493
  }
56
494
  export { BaseGateway };