@sdflc/backend-helpers 1.0.112 → 1.0.114

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) 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 +586 -33
  5. package/build/BaseCore.js +821 -127
  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/IpRateLimiter.d.ts +105 -0
  19. package/build/IpRateLimiter.js +104 -0
  20. package/build/RedisDataLoader.d.ts +144 -21
  21. package/build/RedisDataLoader.js +178 -49
  22. package/build/apiContext.d.ts +0 -8
  23. package/build/apiContext.js +30 -32
  24. package/build/checkItHelpers.d.ts +32 -0
  25. package/build/checkItHelpers.js +73 -7
  26. package/build/commonValidators.d.ts +107 -16
  27. package/build/commonValidators.js +211 -106
  28. package/build/configBuilder.d.ts +23 -0
  29. package/build/configBuilder.js +73 -0
  30. package/build/constants.d.ts +134 -17
  31. package/build/constants.js +95 -15
  32. package/build/dbHelpers.d.ts +89 -29
  33. package/build/dbHelpers.js +175 -86
  34. package/build/dbSeeder.d.ts +10 -1
  35. package/build/dbSeeder.js +80 -15
  36. package/build/dbTableHelpers.d.ts +122 -5
  37. package/build/dbTableHelpers.js +151 -13
  38. package/build/downloadHelpers.d.ts +24 -1
  39. package/build/downloadHelpers.js +51 -21
  40. package/build/esm/BaseController.d.ts +20 -0
  41. package/build/esm/BaseController.js +58 -0
  42. package/build/esm/BaseCore.d.ts +586 -33
  43. package/build/esm/BaseCore.js +812 -118
  44. package/build/esm/BaseExternalApiGateway.d.ts +16 -0
  45. package/build/esm/BaseExternalApiGateway.js +48 -0
  46. package/build/esm/BaseGateway.d.ts +455 -17
  47. package/build/esm/BaseGateway.js +503 -57
  48. package/build/esm/BaseRestApiCrudController.d.ts +37 -0
  49. package/build/esm/BaseRestApiCrudController.js +131 -0
  50. package/build/esm/DataCache.d.ts +116 -5
  51. package/build/esm/DataCache.js +142 -20
  52. package/build/esm/Database.d.ts +165 -4
  53. package/build/esm/Database.js +224 -51
  54. package/build/esm/DbMigratorAndSeeder.d.ts +127 -26
  55. package/build/esm/DbMigratorAndSeeder.js +184 -71
  56. package/build/esm/IpRateLimiter.d.ts +105 -0
  57. package/build/esm/IpRateLimiter.js +100 -0
  58. package/build/esm/RedisDataLoader.d.ts +144 -21
  59. package/build/esm/RedisDataLoader.js +179 -50
  60. package/build/esm/apiContext.d.ts +0 -8
  61. package/build/esm/apiContext.js +30 -32
  62. package/build/esm/checkItHelpers.d.ts +32 -0
  63. package/build/esm/checkItHelpers.js +73 -7
  64. package/build/esm/commonValidators.d.ts +107 -16
  65. package/build/esm/commonValidators.js +209 -105
  66. package/build/esm/configBuilder.d.ts +23 -0
  67. package/build/esm/configBuilder.js +69 -0
  68. package/build/esm/constants.d.ts +134 -17
  69. package/build/esm/constants.js +94 -14
  70. package/build/esm/dbHelpers.d.ts +89 -29
  71. package/build/esm/dbHelpers.js +171 -81
  72. package/build/esm/dbSeeder.d.ts +10 -1
  73. package/build/esm/dbSeeder.js +81 -16
  74. package/build/esm/dbTableHelpers.d.ts +122 -5
  75. package/build/esm/dbTableHelpers.js +152 -14
  76. package/build/esm/downloadHelpers.d.ts +24 -1
  77. package/build/esm/downloadHelpers.js +51 -21
  78. package/build/esm/index.d.ts +6 -2
  79. package/build/esm/index.js +6 -2
  80. package/build/esm/interfaces/ApiContext.d.ts +33 -3
  81. package/build/esm/interfaces/ApiContext.js +1 -0
  82. package/build/esm/interfaces/ApiContextInterface.d.ts +1 -1
  83. package/build/esm/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  84. package/build/esm/interfaces/BaseControllerPropsInterface.js +1 -0
  85. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  86. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  87. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +146 -9
  88. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  89. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  90. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.js +2 -0
  91. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  92. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  93. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  94. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.js +2 -0
  95. package/build/esm/interfaces/BuildConfigOptions.d.ts +18 -0
  96. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  97. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  98. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  99. package/build/esm/interfaces/CacheInterface.d.ts +18 -1
  100. package/build/esm/interfaces/CacheInterface.js +1 -0
  101. package/build/esm/interfaces/CoreActionInterface.d.ts +60 -0
  102. package/build/esm/interfaces/CoreActionInterface.js +1 -0
  103. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +38 -4
  104. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  105. package/build/esm/interfaces/DataCachePropsInterface.d.ts +21 -0
  106. package/build/esm/interfaces/DataCachePropsInterface.js +2 -0
  107. package/build/esm/interfaces/DatabaseOptions.d.ts +24 -10
  108. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  109. package/build/esm/interfaces/DatabaseReadInterface.d.ts +58 -3
  110. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  111. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  112. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  113. package/build/esm/interfaces/DownloadFileArgs.d.ts +21 -2
  114. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  115. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  116. package/build/esm/interfaces/ListArgsInterface.d.ts +18 -0
  117. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  118. package/build/esm/interfaces/LoaderInterface.d.ts +36 -1
  119. package/build/esm/interfaces/LoaderInterface.js +1 -0
  120. package/build/esm/interfaces/UserTokenParams.d.ts +23 -5
  121. package/build/esm/interfaces/UserTokenParams.js +1 -0
  122. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  123. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  124. package/build/esm/interfaces/index.d.ts +4 -0
  125. package/build/esm/interfaces/index.js +4 -0
  126. package/build/esm/knexConfigBuilder.d.ts +25 -0
  127. package/build/esm/knexConfigBuilder.js +100 -36
  128. package/build/esm/parseIds.d.ts +6 -0
  129. package/build/esm/parseIds.js +13 -0
  130. package/build/esm/passwordHelpers.d.ts +22 -0
  131. package/build/esm/passwordHelpers.js +40 -8
  132. package/build/esm/redisClient.d.ts +57 -4
  133. package/build/esm/redisClient.js +40 -54
  134. package/build/esm/resolveClientIp.d.ts +15 -0
  135. package/build/esm/resolveClientIp.js +34 -0
  136. package/build/esm/resolversHelpers.d.ts +21 -1
  137. package/build/esm/resolversHelpers.js +48 -26
  138. package/build/esm/userToken.d.ts +50 -1
  139. package/build/esm/userToken.js +85 -20
  140. package/build/esm/utils.d.ts +20 -2
  141. package/build/esm/utils.js +23 -13
  142. package/build/index.d.ts +6 -2
  143. package/build/index.js +6 -2
  144. package/build/interfaces/ApiContext.d.ts +33 -3
  145. package/build/interfaces/ApiContext.js +1 -0
  146. package/build/interfaces/ApiContextInterface.d.ts +1 -1
  147. package/build/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  148. package/build/interfaces/BaseControllerPropsInterface.js +2 -0
  149. package/build/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  150. package/build/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  151. package/build/interfaces/BaseCorePropsInterface.d.ts +146 -9
  152. package/build/interfaces/BaseCorePropsInterface.js +1 -0
  153. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  154. package/build/interfaces/BaseExternalApiGatewayPropsInterface.js +3 -0
  155. package/build/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  156. package/build/interfaces/BaseGatewayPropsInterface.js +1 -0
  157. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  158. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.js +3 -0
  159. package/build/interfaces/BuildConfigOptions.d.ts +18 -0
  160. package/build/interfaces/BuildConfigOptions.js +1 -0
  161. package/build/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  162. package/build/interfaces/BuildListQueryArgsInterface.js +1 -0
  163. package/build/interfaces/CacheInterface.d.ts +18 -1
  164. package/build/interfaces/CacheInterface.js +1 -0
  165. package/build/interfaces/CoreActionInterface.d.ts +60 -0
  166. package/build/interfaces/CoreActionInterface.js +1 -0
  167. package/build/interfaces/CreateUserTokenArgs.d.ts +38 -4
  168. package/build/interfaces/CreateUserTokenArgs.js +1 -0
  169. package/build/interfaces/DataCachePropsInterface.d.ts +21 -0
  170. package/build/interfaces/DataCachePropsInterface.js +3 -0
  171. package/build/interfaces/DatabaseOptions.d.ts +24 -10
  172. package/build/interfaces/DatabaseOptions.js +1 -0
  173. package/build/interfaces/DatabaseReadInterface.d.ts +58 -3
  174. package/build/interfaces/DatabaseReadInterface.js +1 -0
  175. package/build/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  176. package/build/interfaces/DbFieldAddDefaultInterface.js +1 -0
  177. package/build/interfaces/DownloadFileArgs.d.ts +21 -2
  178. package/build/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  179. package/build/interfaces/ExtractCredentialsArgs.js +1 -0
  180. package/build/interfaces/ListArgsInterface.d.ts +18 -0
  181. package/build/interfaces/ListArgsInterface.js +1 -0
  182. package/build/interfaces/LoaderInterface.d.ts +36 -1
  183. package/build/interfaces/LoaderInterface.js +1 -0
  184. package/build/interfaces/UserTokenParams.d.ts +23 -5
  185. package/build/interfaces/UserTokenParams.js +1 -0
  186. package/build/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  187. package/build/interfaces/VerifyUserTokenArgs.js +1 -0
  188. package/build/interfaces/index.d.ts +4 -0
  189. package/build/interfaces/index.js +4 -0
  190. package/build/knexConfigBuilder.d.ts +25 -0
  191. package/build/knexConfigBuilder.js +99 -35
  192. package/build/parseIds.d.ts +6 -0
  193. package/build/parseIds.js +17 -0
  194. package/build/passwordHelpers.d.ts +22 -0
  195. package/build/passwordHelpers.js +40 -8
  196. package/build/redisClient.d.ts +57 -4
  197. package/build/redisClient.js +40 -54
  198. package/build/resolveClientIp.d.ts +15 -0
  199. package/build/resolveClientIp.js +38 -0
  200. package/build/resolversHelpers.d.ts +21 -1
  201. package/build/resolversHelpers.js +48 -26
  202. package/build/userToken.d.ts +50 -1
  203. package/build/userToken.js +85 -20
  204. package/build/utils.d.ts +20 -2
  205. package/build/utils.js +24 -16
  206. package/package.json +19 -18
  207. package/build/baseController.d.ts +0 -17
  208. package/build/baseController.js +0 -64
  209. package/build/configBulder.d.ts +0 -2
  210. package/build/configBulder.js +0 -36
  211. package/build/esm/baseController.d.ts +0 -17
  212. package/build/esm/baseController.js +0 -58
  213. package/build/esm/configBulder.d.ts +0 -2
  214. package/build/esm/configBulder.js +0 -32
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ // ./src/BaseGateway.ts
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
5
  };
@@ -12,85 +13,202 @@ const utils_1 = require("@sdflc/utils");
12
13
  const DataCache_1 = require("./DataCache");
13
14
  const constants_1 = require("./constants");
14
15
  const DEFAULT_CHUNCK_SIZE = 2500;
16
+ /**
17
+ * BaseGateway is the foundation for all database-backed gateway classes.
18
+ *
19
+ * A gateway is a low-level data-access object responsible for a single
20
+ * database table. It handles CRUD operations, cache management, soft-delete
21
+ * patterns, field transforms, and query filtering.
22
+ *
23
+ * Gateways are instantiated per-request — they receive a full ApiContext
24
+ * (including db, spaceId, userId etc.) at construction time and must not
25
+ * be reused across requests. This is critical because `dateTimeNow` and all
26
+ * context-derived values (userId, spaceId) are snapshotted at construction.
27
+ *
28
+ * Subclasses typically override:
29
+ * - `onListFilter()` — to add resource-specific WHERE clauses
30
+ * - `onUpdateFilter()` — to add resource-specific update conditions
31
+ * - `onRemoveFilter()` — to add resource-specific remove conditions
32
+ * - `transformOnOut()` — to shape outbound records (e.g. rename fields,
33
+ * attach computed properties)
34
+ * - `generateId()` — to use a domain-specific ID strategy
35
+ *
36
+ * The loader (DataCache by default) is used for batched per-id loading
37
+ * via DataLoader semantics. It is bypassed when `noCache: true` is set in
38
+ * config, or when `list()` is called with `useCache: false`.
39
+ */
15
40
  class BaseGateway {
16
41
  config;
17
42
  logger;
18
43
  loader;
19
44
  dateTime = new utils_1.DateTimeHelpers();
45
+ /**
46
+ * Timestamp captured at construction time. Used as the value for
47
+ * createdAt / updatedAt / removedAt fields so that all writes within
48
+ * a single request share the same timestamp.
49
+ *
50
+ * IMPORTANT: This is set once at instantiation — gateways must be
51
+ * created per-request. Reusing a gateway instance across requests will
52
+ * result in stale timestamps being written to the database.
53
+ */
20
54
  dateTimeNow = new Date();
21
55
  constructor(props) {
22
56
  this.config = props;
57
+ // Normalise returnFields — default to ['*'] if not provided or empty.
58
+ // returnFields controls which columns are included in INSERT/UPDATE RETURNING clauses.
23
59
  this.config.returnFields =
24
60
  Array.isArray(this.config.returnFields) && this.config.returnFields.length > 0 ? this.config.returnFields : ['*'];
61
+ // Normalise activeStatuses — used by onListFilter when no explicit status
62
+ // filter is provided in the query params.
25
63
  this.config.activeStatuses = Array.isArray(this.config.activeStatuses)
26
64
  ? this.config.activeStatuses
27
65
  : [utils_1.STATUSES.ACTIVE];
66
+ // keyPrefix is used to namespace DataLoader cache keys. It falls back through
67
+ // context.keyPrefix → config.keyPrefix → table name, in that order.
28
68
  this.config.keyPrefix = this.config.context?.keyPrefix || this.config.keyPrefix || this.config.table;
69
+ // Enforce uniqueness of keyPrefix within a single request context.
70
+ // Two gateways with the same keyPrefix would share a DataLoader cache,
71
+ // causing one gateway's cached records to be returned for another's queries.
29
72
  if (this.config.keyPrefix && this.config.context?.usedKeyPrefixes) {
30
73
  if (this.config.context.usedKeyPrefixes[this.config.keyPrefix]) {
31
- throw new Error(`The "${this.config.keyPrefix}" is already used as the "keyPrefix" in the application. Please use another one that is not as: ${Object.keys(this.config.context.usedKeyPrefixes).join(', ')}`);
74
+ throw new Error(`The "${this.config.keyPrefix}" is already used as the "keyPrefix" in the application. ` +
75
+ `Please use another one that is not: ${Object.keys(this.config.context.usedKeyPrefixes).join(', ')}`);
32
76
  }
33
77
  this.config.context.usedKeyPrefixes[this.config.keyPrefix] = true;
34
78
  }
35
- this.logger = props?.logger instanceof utils_1.Logger ? props.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.WARNING });
79
+ // Duck-type check instead of instanceof to avoid false negatives when
80
+ // the consuming app has a different installed version of @sdflc/utils,
81
+ // which would produce a different Logger class reference.
82
+ this.logger = props?.logger && (0, utils_1.isLogger)(props?.logger) ? props.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.WARNING });
83
+ // If a custom loader function is provided in config, use it directly.
84
+ // Otherwise fall back to the default DataCache, which wraps DataLoader
85
+ // for batched, per-request in-memory caching.
36
86
  this.loader = check_types_1.default.function(this.config?.loader) ? this.config.loader : new DataCache_1.DataCache(this.config);
37
87
  }
88
+ /**
89
+ * Returns the full gateway config object.
90
+ * Useful for subclasses or external code that needs to inspect configuration
91
+ * without accessing protected fields directly.
92
+ */
38
93
  getConfig() {
39
94
  return this.config;
40
95
  }
96
+ /**
97
+ * Merges the provided props into the existing config.
98
+ * Allows runtime config changes (e.g. swapping the table, adjusting chunk size)
99
+ * without recreating the gateway.
100
+ *
101
+ * Returns `this` for chaining.
102
+ */
41
103
  setConfigPart(props) {
42
104
  Object.assign(this.config, props);
43
105
  return this;
44
106
  }
107
+ /**
108
+ * Replaces the loader used for `get()` and `getMany()` calls.
109
+ * The loader must implement the `LoaderInterface` (i.e. `load` and `loadMany`).
110
+ *
111
+ * Use this to inject a custom DataLoader, a mock in tests, or a loader
112
+ * backed by a different cache layer (Redis, etc.).
113
+ *
114
+ * Returns `this` for chaining.
115
+ */
45
116
  setLoader(loader) {
46
117
  this.loader = loader;
47
118
  return this;
48
119
  }
120
+ /**
121
+ * Replaces the loader with a new DataCache instance built from the
122
+ * provided cache config merged with the existing gateway config.
123
+ *
124
+ * Use this when you want to adjust caching behaviour (TTL, batch size, etc.)
125
+ * without providing a fully custom loader.
126
+ *
127
+ * Returns `this` for chaining.
128
+ */
49
129
  setLoaderConfig(config) {
50
130
  this.loader = new DataCache_1.DataCache({ ...this.config, ...config });
51
131
  return this;
52
132
  }
53
133
  /**
54
- * Generates object's ID
55
- * @param object use them when overriding the generate method and you may need data from an object
56
- * @returns unique ID, by default it is UUID v4
134
+ * Generates a unique ID for a new record.
135
+ *
136
+ * Defaults to UUID v4. Override in a subclass to use a different ID
137
+ * strategy (e.g. nanoid, sequential IDs, composite keys).
138
+ *
139
+ * The `object` parameter is the record about to be inserted — it is
140
+ * available in case the ID needs to be derived from the object's data.
57
141
  */
58
- async generateId(object) {
142
+ async generateId(_object) {
59
143
  return (0, uuid_1.v4)();
60
144
  }
145
+ /**
146
+ * Applies WHERE clauses to a list query based on the provided filter params.
147
+ * Called internally by `list()` after the base query is built.
148
+ *
149
+ * Override in subclasses to add resource-specific filters. Always call
150
+ * `super.onListFilter(query, filterParams)` first to preserve the standard
151
+ * filtering behaviour (status, spaceId, lang, keyword, etc.).
152
+ *
153
+ * Built-in filter behaviours (each controlled by a config flag):
154
+ * - `hasStatus` — filters by status; defaults to activeStatuses if
155
+ * no status param is provided
156
+ * - `hasRemovedAt` — excludes soft-deleted records (removedAt IS NULL)
157
+ * - `hasSpace` — scopes to the current spaceId from context or params
158
+ * - `hasLang` — filters by language
159
+ * - `fieldForKeyword` — applies a case-insensitive LIKE on the configured field
160
+ * - `filterByUserField` — scopes to the current userId from context
161
+ *
162
+ * Nuance: `hasSpace` checks both `filterParams[SPACE_ID]` and
163
+ * `context.spaceId`, preferring the explicit param. If neither is set and
164
+ * `hasSpace` is true, the filter is skipped entirely — no space scoping.
165
+ */
61
166
  async onListFilter(query, filterParams) {
62
167
  const { table, hasStatus, hasRemovedAt, hasSpace, activeStatuses, hasLang, fieldForKeyword, filterByUserField } = this.config || {};
63
- // This function should be overriden
64
168
  if (hasStatus) {
65
169
  query.whereIn(`${table}.${constants_1.FIELDS.STATUS}`, filterParams?.[constants_1.FIELDS.STATUS] != null ? (0, lodash_1.castArray)(filterParams?.[constants_1.FIELDS.STATUS]) : (0, lodash_1.castArray)(activeStatuses));
66
170
  }
67
171
  if (hasRemovedAt) {
68
172
  query.whereNull(`${table}.${constants_1.FIELDS.REMOVED_AT}`);
69
173
  }
70
- if (hasSpace && (filterParams?.[constants_1.FIELDS.SPACE_ID] != undefined || this.config.context.spaceId)) {
174
+ if (hasSpace && (filterParams?.[constants_1.FIELDS.SPACE_ID] != undefined || this.config.context?.spaceId)) {
71
175
  query.where({
72
- [`${table}.${constants_1.FIELDS.SPACE_ID}`]: filterParams?.[constants_1.FIELDS.SPACE_ID] != undefined ? filterParams?.[constants_1.FIELDS.SPACE_ID] : this.config.context.spaceId,
176
+ [`${table}.${constants_1.FIELDS.SPACE_ID}`]: filterParams?.[constants_1.FIELDS.SPACE_ID] != undefined ? filterParams?.[constants_1.FIELDS.SPACE_ID] : this.config.context?.spaceId,
73
177
  });
74
178
  }
75
179
  if (hasLang && filterParams?.[constants_1.FIELDS.LANG] != undefined) {
76
180
  query.whereIn(`${table}.${constants_1.FIELDS.LANG}`, (0, lodash_1.castArray)(filterParams?.[constants_1.FIELDS.LANG]));
77
181
  }
182
+ // Allow filtering by the id field directly in filterParams.
183
+ // Supports both simple column names and qualified names (table.column).
78
184
  const idField = this.getIdField();
79
185
  if (filterParams?.[idField]) {
80
- query.whereIn(idField.includes('.') ? `${idField}` : `${table}.${idField}`, (0, lodash_1.castArray)(filterParams?.[idField]));
186
+ query.whereIn(idField.includes('.') ? idField : `${table}.${idField}`, (0, lodash_1.castArray)(filterParams?.[idField]));
81
187
  }
82
188
  if (fieldForKeyword && filterParams.keyword) {
83
- // const opLike = this.getDb().getDbType() === 'pg' ? 'ILIKE' : 'LIKE';
84
- // query.whereRaw(`?? ${opLike} ?`, [fieldForKeyword, `%${filterParams.keyword}%`]);
85
189
  query.whereILike(fieldForKeyword, `%${filterParams.keyword}%`);
86
190
  }
87
191
  if (filterByUserField) {
88
- query.where({ [filterByUserField]: this.getContext().userId });
192
+ query.where({ [filterByUserField]: this.getContext()?.userId });
89
193
  }
90
- // TODO: prse filterParams and buils where clause automatically here
91
194
  }
195
+ /**
196
+ * Applies WHERE clauses to an update query based on the provided filter params.
197
+ * Called internally by `update()` after the UPDATE statement is prepared.
198
+ *
199
+ * Returns the number of filter conditions applied. If this is 0, `update()`
200
+ * will throw to prevent an unfiltered UPDATE from affecting all rows.
201
+ *
202
+ * Override in subclasses to add resource-specific update conditions.
203
+ * Always call `super.onUpdateFilter()` first.
204
+ *
205
+ * Built-in filter behaviours:
206
+ * - Always filters by the id field (idFieldUpdateRemove) when present
207
+ * - `hasVersion` — adds an optimistic-lock check on the version field,
208
+ * preventing updates if the version has changed since the record was read
209
+ * - `hasStatus` — excludes already-removed records from being updated
210
+ */
92
211
  async onUpdateFilter(query, filterParams) {
93
- // This function should be overriden
94
212
  const { hasStatus, hasVersion } = this.config;
95
213
  const idName = this.getIdFieldUpdateRemove();
96
214
  let filtersAppliedQty = 0;
@@ -115,14 +233,30 @@ class BaseGateway {
115
233
  }
116
234
  return filtersAppliedQty;
117
235
  }
236
+ /**
237
+ * Applies WHERE clauses to a remove query based on the provided filter params.
238
+ * Called internally by `remove()` after the DELETE/UPDATE statement is prepared.
239
+ *
240
+ * Returns the number of filter conditions applied. If this is 0, `remove()`
241
+ * will throw to prevent an unfiltered DELETE or soft-delete UPDATE.
242
+ *
243
+ * `filterParams` can be a single object or an array of objects. The method
244
+ * collects the id field value from each entry and applies a single whereIn.
245
+ *
246
+ * Override in subclasses to add resource-specific remove conditions.
247
+ * Always call `super.onRemoveFilter()` first.
248
+ *
249
+ * Built-in filter behaviours:
250
+ * - Collects the id field (idFieldUpdateRemove) from each item in filterParams
251
+ * - `hasStatus` — adds a guard to prevent double-removal of already-removed records
252
+ */
118
253
  async onRemoveFilter(query, filterParams) {
119
- // This function should be overriden
120
254
  const { hasStatus } = this.config;
121
255
  const arr = filterParams ? (0, lodash_1.castArray)(filterParams) : [];
122
256
  let filtersAppliedQty = 0;
123
257
  const idName = this.getIdFieldUpdateRemove();
124
258
  const ids = [];
125
- for (let filter of arr) {
259
+ for (const filter of arr) {
126
260
  if (filter[idName]) {
127
261
  ids.push(filter[idName]);
128
262
  }
@@ -137,6 +271,27 @@ class BaseGateway {
137
271
  }
138
272
  return filtersAppliedQty;
139
273
  }
274
+ /**
275
+ * Transforms a params object before it is inserted into the database.
276
+ * Called once per object inside the `create()` loop, after the ID is generated.
277
+ *
278
+ * Mutates and returns the params object. Override in subclasses to add
279
+ * computed fields, enforce defaults, or validate data before insert.
280
+ * Always call `super.transformOnCreate(params)` first.
281
+ *
282
+ * Built-in transformations (each controlled by a config flag):
283
+ * - `hasCreatedAt` — sets createdAt to the gateway's construction timestamp
284
+ * - `hasCreatedBy` — sets createdBy to context.userId if not already set
285
+ * - `hasUserId` — sets userId to context.userId if not already set
286
+ * - `hasSpace` — sets spaceId from context (always overwritten)
287
+ * - `hasVersion` — initialises version to 0
288
+ * - `hasLang` + `localizationForField` — builds a composite id from the
289
+ * localisation field value and the lang field (e.g. "slug_en")
290
+ *
291
+ * Nuance: createdBy and userId are only set if not already present in params,
292
+ * allowing the caller to supply an explicit value (e.g. when migrating data).
293
+ * spaceId, by contrast, is always overwritten from context to prevent spoofing.
294
+ */
140
295
  async transformOnCreate(params) {
141
296
  const { hasCreatedAt, hasCreatedBy, hasSpace, hasVersion, hasLang, localizationForField, hasUserId } = this.config;
142
297
  if (hasCreatedAt) {
@@ -145,17 +300,17 @@ class BaseGateway {
145
300
  if (hasCreatedBy) {
146
301
  const createdBy = (0, lodash_1.camelCase)(constants_1.FIELDS.CREATED_BY);
147
302
  if (params[createdBy] === undefined) {
148
- params[createdBy] = this.getContext().userId;
303
+ params[createdBy] = this.getContext()?.userId;
149
304
  }
150
305
  }
151
306
  if (hasUserId) {
152
307
  const userId = (0, lodash_1.camelCase)(constants_1.FIELDS.USER_ID);
153
308
  if (params[userId] === undefined) {
154
- params[userId] = this.getContext().userId;
309
+ params[userId] = this.getContext()?.userId;
155
310
  }
156
311
  }
157
312
  if (hasSpace) {
158
- params[(0, lodash_1.camelCase)(constants_1.FIELDS.SPACE_ID)] = this.getContext().spaceId;
313
+ params[(0, lodash_1.camelCase)(constants_1.FIELDS.SPACE_ID)] = this.getContext()?.spaceId;
159
314
  }
160
315
  if (hasVersion) {
161
316
  params[(0, lodash_1.camelCase)(constants_1.FIELDS.VERSION)] = 0;
@@ -165,6 +320,29 @@ class BaseGateway {
165
320
  }
166
321
  return params;
167
322
  }
323
+ /**
324
+ * Transforms a params object before it is applied as an UPDATE in the database.
325
+ * Called by `update()`, `increment()`, and `decrement()` before the query runs.
326
+ *
327
+ * Mutates and returns the params object. Override in subclasses to add
328
+ * computed fields or enforce constraints before update.
329
+ * Always call `super.transformOnUpdate(params, where)` first.
330
+ *
331
+ * The `where` parameter carries the filter criteria (including the id) and is
332
+ * available for subclasses that need to derive update values from the filter.
333
+ *
334
+ * Built-in transformations:
335
+ * - `hasUpdatedAt` — sets updatedAt to the gateway's construction timestamp
336
+ * - `hasUpdatedBy` — sets updatedBy to context.userId if not already set
337
+ * - `hasVersion` — increments version by 1 (only if version is present
338
+ * and numeric in params; no-op otherwise)
339
+ * - `hasLang` + `localizationForField` — rebuilds the composite id from the
340
+ * localisation field value and lang (same logic as transformOnCreate)
341
+ *
342
+ * Nuance: version increment only fires if the version is already present in
343
+ * params. This allows callers to explicitly omit version management when needed
344
+ * (e.g. admin operations that should not bump the version).
345
+ */
168
346
  async transformOnUpdate(params, where) {
169
347
  const { hasUpdatedAt, hasUpdatedBy, hasVersion, hasLang, localizationForField } = this.config;
170
348
  if (hasUpdatedAt) {
@@ -173,7 +351,7 @@ class BaseGateway {
173
351
  if (hasUpdatedBy) {
174
352
  const updatedBy = (0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_BY);
175
353
  if (params[updatedBy] === undefined) {
176
- params[updatedBy] = this.getContext().userId;
354
+ params[updatedBy] = this.getContext()?.userId;
177
355
  }
178
356
  }
179
357
  if (hasVersion) {
@@ -187,6 +365,31 @@ class BaseGateway {
187
365
  }
188
366
  return params;
189
367
  }
368
+ /**
369
+ * Transforms a params object before it is applied as an upsert (INSERT ... ON CONFLICT MERGE).
370
+ * Called by `set()` for each object before the batch is inserted.
371
+ *
372
+ * This is a superset of both `transformOnCreate` and `transformOnUpdate`:
373
+ * it applies creation fields (createdAt, createdBy, spaceId) AND update fields
374
+ * (updatedAt, updatedBy) in a single pass, making it suitable for upserts where
375
+ * you don't know in advance whether the record already exists.
376
+ *
377
+ * Mutates and returns the params object. Override in subclasses as needed.
378
+ * Always call `super.transformOnSet(params)` first.
379
+ *
380
+ * Built-in transformations:
381
+ * - `hasCreatedAt` — sets createdAt (will be skipped in the ON CONFLICT
382
+ * MERGE clause via skipFields — existing records keep
383
+ * their original createdAt)
384
+ * - `hasCreatedBy` — sets createdBy if not already set (also skipped on merge)
385
+ * - `hasUserId` — sets userId if not already set
386
+ * - `hasSpace` — sets spaceId (also skipped on merge)
387
+ * - `hasUpdatedAt` — sets updatedAt (always merged on conflict)
388
+ * - `hasUpdatedBy` — sets updatedBy if not already set
389
+ * - `hasVersion` — increments version if present and numeric,
390
+ * otherwise initialises to 0 (create path)
391
+ * - `hasLang` + `localizationForField` — builds composite id from localisation field + lang
392
+ */
190
393
  async transformOnSet(params) {
191
394
  const { hasCreatedAt, hasCreatedBy, hasSpace, hasUpdatedAt, hasUpdatedBy, hasVersion, hasLang, localizationForField, hasUserId, } = this.config;
192
395
  if (hasCreatedAt) {
@@ -195,17 +398,17 @@ class BaseGateway {
195
398
  if (hasCreatedBy) {
196
399
  const createdBy = (0, lodash_1.camelCase)(constants_1.FIELDS.CREATED_BY);
197
400
  if (params[createdBy] === undefined) {
198
- params[createdBy] = this.getContext().userId;
401
+ params[createdBy] = this.getContext()?.userId;
199
402
  }
200
403
  }
201
404
  if (hasUserId) {
202
405
  const userId = (0, lodash_1.camelCase)(constants_1.FIELDS.USER_ID);
203
406
  if (params[userId] === undefined) {
204
- params[userId] = this.getContext().userId;
407
+ params[userId] = this.getContext()?.userId;
205
408
  }
206
409
  }
207
410
  if (hasSpace) {
208
- params[(0, lodash_1.camelCase)(constants_1.FIELDS.SPACE_ID)] = this.getContext().spaceId;
411
+ params[(0, lodash_1.camelCase)(constants_1.FIELDS.SPACE_ID)] = this.getContext()?.spaceId;
209
412
  }
210
413
  if (hasUpdatedAt) {
211
414
  params[(0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
@@ -213,7 +416,7 @@ class BaseGateway {
213
416
  if (hasUpdatedBy) {
214
417
  const updatedBy = (0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_BY);
215
418
  if (params[updatedBy] === undefined) {
216
- params[updatedBy] = this.getContext().userId;
419
+ params[updatedBy] = this.getContext()?.userId;
217
420
  }
218
421
  }
219
422
  if (hasVersion) {
@@ -230,13 +433,41 @@ class BaseGateway {
230
433
  }
231
434
  return params;
232
435
  }
436
+ /**
437
+ * Builds the patch object applied to a record when it is soft-deleted.
438
+ * Called by `remove()` when `hardRemove` is false and `hasRemovedAt` is true.
439
+ *
440
+ * Returns a new object (merged from `args`) with removal fields populated.
441
+ * Override in subclasses to add custom soft-delete fields.
442
+ * Always call `super.transformOnRemove(args)` first.
443
+ *
444
+ * The `args` parameter is the original `where` filter passed to `remove()`.
445
+ * It is available so subclasses can derive removal values from the filter
446
+ * (e.g. storing which id was removed). In the base implementation it is
447
+ * spread into the patch object as-is.
448
+ *
449
+ * Built-in transformations:
450
+ * - `hasRemovedAt` — sets removedAt to the current time (dayjs, not
451
+ * dateTimeNow — removal time is always real-time,
452
+ * not the gateway construction timestamp)
453
+ * - `hasRemovedAtStr` — sets removedAtStr to a formatted string timestamp
454
+ * (YYYYMMDDTHHmmssZ), useful for building composite
455
+ * keys that need to encode the removal time
456
+ * - `hasStatus` — sets status to STATUSES.REMOVED
457
+ * - `hasRemovedBy` — sets removedBy to context.userId if not already set
458
+ * - `hasLang` + `localizationForField` — appends the removal timestamp to
459
+ * the id field using a raw CONCAT expression, so
460
+ * the old localisation key is freed up for re-use
461
+ *
462
+ * Nuance: removedAt uses `dayjs()` (current time) rather than `dateTimeNow`
463
+ * (construction time). This is intentional — removal timestamps should be
464
+ * as accurate as possible and are not batch-grouped like create/update times.
465
+ */
233
466
  async transformOnRemove(args) {
234
467
  const { hasRemovedAt, hasRemovedAtStr, hasStatus, hasRemovedBy, hasLang, localizationForField } = this.config;
235
468
  const removalTime = (0, dayjs_1.default)();
236
469
  const removalTimeStr = removalTime.format('YYYYMMDDTHHmmssZ');
237
- const obj = {
238
- ...(args || {}),
239
- };
470
+ const obj = { ...(args || {}) };
240
471
  if (hasRemovedAt) {
241
472
  obj[constants_1.FIELDS.REMOVED_AT] = removalTime.toDate();
242
473
  }
@@ -248,50 +479,159 @@ class BaseGateway {
248
479
  }
249
480
  if (hasRemovedBy) {
250
481
  if (obj[constants_1.FIELDS.REMOVED_BY] === undefined) {
251
- obj[constants_1.FIELDS.REMOVED_BY] = this.getContext().userId;
482
+ obj[constants_1.FIELDS.REMOVED_BY] = this.getContext()?.userId;
252
483
  }
253
484
  }
254
485
  if (hasLang && localizationForField) {
486
+ // Append removal timestamp to the id to free the original localisation key
487
+ // for future re-use (e.g. if a new record with the same lang + slug is created).
255
488
  obj[this.getIdField()] = this.getDb().raw(`CONCAT(id, '-${removalTimeStr}')`);
256
489
  }
257
490
  return obj;
258
491
  }
492
+ /**
493
+ * Transforms a record after it is read from the database, before it is
494
+ * returned to the caller.
495
+ *
496
+ * The base implementation is a no-op — it returns the item unchanged.
497
+ * Override in subclasses to rename fields, attach computed properties,
498
+ * strip sensitive columns, or convert types (e.g. parse JSON strings).
499
+ *
500
+ * Called by: `list()`, `create()`, `update()`, `updateMany()`,
501
+ * `increment()`, `decrement()`, `set()`, `remove()`.
502
+ *
503
+ * Note: `get()` and `getMany()` go through the loader (DataCache/DataLoader)
504
+ * and do NOT call `transformOnOut()` — transformations on cached records
505
+ * must be handled in the loader's priming logic or in the calling code.
506
+ */
259
507
  transformOnOut(item) {
260
508
  return item;
261
509
  }
510
+ /**
511
+ * Returns the requestId from the current ApiContext.
512
+ * Useful for correlating log entries or error reports to a specific request.
513
+ */
262
514
  getRequestId() {
263
515
  return this.config.context.requestId;
264
516
  }
517
+ /**
518
+ * Returns the full ApiContext associated with this gateway instance.
519
+ * The context carries request-scoped values: userId, spaceId, headers,
520
+ * other gateways, cores, db, etc.
521
+ */
265
522
  getContext() {
266
523
  return this.config.context;
267
524
  }
525
+ /**
526
+ * Returns all gateway instances from the current request context.
527
+ * Allows one gateway to call another (e.g. UserGateway calling RoleGateway)
528
+ * without going through a core, using the same shared context and db connection.
529
+ *
530
+ * Returns an empty object if context is not available.
531
+ */
268
532
  getGateways() {
269
- return this.config.context.gateways || {};
533
+ return this.config.context?.gateways || {};
270
534
  }
535
+ /**
536
+ * Returns the Database instance from config.
537
+ * All query builders are derived from this instance.
538
+ */
271
539
  getDb() {
272
540
  return this.config.db;
273
541
  }
542
+ /**
543
+ * Returns a Knex query builder scoped to this gateway's table.
544
+ * The builder is a fresh instance each time — it does not carry state
545
+ * between calls.
546
+ */
274
547
  getBuilder() {
275
548
  return this.getDb()?.getBuilder(this.config.table);
276
549
  }
550
+ /**
551
+ * Returns the primary key field name used for SELECT and loader operations.
552
+ * Defaults to the global ID_FIELD constant if not set in config.
553
+ *
554
+ * Note: this may differ from `getIdFieldUpdateRemove()` — some tables use
555
+ * a different column for update/delete filtering (e.g. a composite key)
556
+ * while listing and loading still uses the primary key.
557
+ */
277
558
  getIdField() {
278
559
  return this.config.idField || constants_1.ID_FIELD;
279
560
  }
561
+ /**
562
+ * Returns the field name used to identify records in UPDATE and DELETE
563
+ * WHERE clauses. Falls back through idFieldUpdateRemove → idField → ID_FIELD.
564
+ *
565
+ * Separate from `getIdField()` to support tables where the logical primary
566
+ * key used for loading differs from the column used for writes
567
+ * (e.g. a table with a UUID primary key but a separate "slug" as update target).
568
+ */
280
569
  getIdFieldUpdateRemove() {
281
570
  return this.config.idFieldUpdateRemove || this.config.idField || constants_1.ID_FIELD;
282
571
  }
572
+ /**
573
+ * Loads a single record by id via the loader (DataCache/DataLoader).
574
+ * Leverages DataLoader batching — multiple `get()` calls within the same
575
+ * tick are coalesced into a single database query.
576
+ *
577
+ * Results are cached for the duration of the request. To bypass the cache,
578
+ * call `list()` with `useCache: false` instead.
579
+ */
283
580
  async get(id) {
284
581
  return this.loader.load(id);
285
582
  }
583
+ /**
584
+ * Loads multiple records by their ids via the loader (DataCache/DataLoader).
585
+ * Returns results in the same order as the input ids array, with `null`
586
+ * entries for any ids that were not found (DataLoader semantics).
587
+ *
588
+ * Leverages DataLoader batching — all ids are fetched in a single query.
589
+ * Results are cached for the duration of the request.
590
+ */
286
591
  async getMany(ids) {
287
592
  return this.loader.loadMany(ids);
288
593
  }
594
+ /**
595
+ * Builds the base SELECT query for `list()`.
596
+ * Override in subclasses to add JOINs, computed columns, or subqueries
597
+ * that should always be present in list results.
598
+ *
599
+ * The `fieldsToUse` argument determines which columns are selected:
600
+ * - When `useCache` is true (default), only the id field is selected —
601
+ * the full records are then fetched via the loader/cache.
602
+ * - When `useCache` is false, `selectFields` from config are used, falling
603
+ * back to '*' if not configured.
604
+ *
605
+ * Returns an object `{ query }` so subclasses can destructure it and
606
+ * attach additional query segments before returning.
607
+ */
289
608
  async buildListQuery(args) {
290
609
  const { fieldsToUse } = args || {};
291
610
  const query = this.getBuilder();
292
611
  query.select(fieldsToUse || '*');
293
612
  return { query };
294
613
  }
614
+ /**
615
+ * Fetches a paginated, filtered list of records from the database.
616
+ *
617
+ * Flow:
618
+ * 1. Builds the base query via `buildListQuery()`
619
+ * 2. Applies filter conditions via `onListFilter()`
620
+ * 3. Applies pagination (limit/offset) and sorting
621
+ * 4. If `useCache` is true, fetches only ids then loads full records
622
+ * via the loader (DataLoader batching + in-memory cache)
623
+ * 5. Transforms each result via `transformOnOut()`
624
+ *
625
+ * Cache behaviour:
626
+ * - `useCache` defaults to `!config.noCache`
627
+ * - When true, the list query selects only id fields, and full records
628
+ * are hydrated through the DataLoader. This means list results benefit
629
+ * from the same cache as `get()` / `getMany()` calls in the same request.
630
+ * - When false, `selectFields` are fetched directly without going through
631
+ * the loader. Use this for aggregations, reports, or large exports.
632
+ *
633
+ * Returns an empty array immediately if `config.table` is not set.
634
+ */
295
635
  async list(args) {
296
636
  const { filter, params, useCache } = args || {};
297
637
  const { limit, offset, sortBy } = this.getDb().createLimitOffsetSortBy(params, this.config.defaultSorting || []);
@@ -312,6 +652,23 @@ class BaseGateway {
312
652
  const result = shouldUseCache ? await this.getMany(items.map((row) => row.id)) : items;
313
653
  return result.map((item) => this.transformOnOut(item));
314
654
  }
655
+ /**
656
+ * Inserts one or more records into the database.
657
+ *
658
+ * Accepts a single object or an array of objects (via castArray).
659
+ * For each object:
660
+ * 1. Generates a new id via `generateId()`
661
+ * 2. Applies `transformOnCreate()` to set audit fields, spaceId, version, etc.
662
+ *
663
+ * Inserts are batched into chunks of `config.insertChunkSize` (default 2500)
664
+ * to avoid hitting database parameter limits on large arrays.
665
+ *
666
+ * Returns all inserted records (via RETURNING), each passed through
667
+ * `transformOnOut()`.
668
+ *
669
+ * Note: does NOT prime the loader cache with the newly created records.
670
+ * Subsequent `get()` calls for these ids will hit the database.
671
+ */
315
672
  async create(args) {
316
673
  const objects = (0, lodash_1.castArray)(args);
317
674
  if (!args || objects.length === 0) {
@@ -321,7 +678,6 @@ class BaseGateway {
321
678
  const object = objects[idx];
322
679
  const id = await this.generateId(object);
323
680
  objects[idx] = await this.transformOnCreate({ id, ...object });
324
- //objects.push(obj);
325
681
  }
326
682
  const result = [];
327
683
  const chunks = (0, utils_1.arrToChunks)(objects, this.config?.insertChunkSize || DEFAULT_CHUNCK_SIZE);
@@ -331,12 +687,33 @@ class BaseGateway {
331
687
  }
332
688
  return result.map((item) => this.transformOnOut(item));
333
689
  }
690
+ /**
691
+ * Updates one or more records matching the `where` filter.
692
+ *
693
+ * Flow:
694
+ * 1. Applies `transformOnUpdate()` to set audit fields and increment version
695
+ * 2. Builds the UPDATE query with RETURNING
696
+ * 3. Applies WHERE conditions via `onUpdateFilter()`
697
+ * 4. Throws if no filter conditions were applied (safety guard against
698
+ * unfiltered updates that would affect all rows)
699
+ * 5. Clears affected records from the loader cache
700
+ * 6. Returns updated records through `transformOnOut()`
701
+ *
702
+ * The `where` object should contain the id field and optionally version
703
+ * (for optimistic locking). Additional filter logic can be added by
704
+ * overriding `onUpdateFilter()`.
705
+ *
706
+ * Nuance: if `hasVersion` is configured and `where` does not include a
707
+ * version, the version check is skipped. This allows unconditional updates
708
+ * (e.g. admin operations) by simply omitting the version from the filter.
709
+ */
334
710
  async update(where, params) {
335
711
  const object = await this.transformOnUpdate(params, where);
336
712
  const query = this.getBuilder().update(object).returning(this.config.returnFields);
337
713
  const filtersAppliedQty = await this.onUpdateFilter(query, where);
338
714
  if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
339
- throw new Error(`Failed to update the table '${this.config.table}' as none of filters applied: ${JSON.stringify(where, null, 2)}`);
715
+ throw new Error(`Failed to update table '${this.config.table}': no filters applied. ` +
716
+ `Expected id field: '${this.getIdFieldUpdateRemove()}'. Received: ${JSON.stringify(where, null, 2)}`);
340
717
  }
341
718
  const items = await query;
342
719
  if (items.length > 0 && this.config.noCache !== true) {
@@ -349,6 +726,20 @@ class BaseGateway {
349
726
  }
350
727
  return items.map((item) => this.transformOnOut(item));
351
728
  }
729
+ /**
730
+ * Updates multiple records, each with its own where filter and params.
731
+ *
732
+ * Accepts an array of `{ where, params }` pairs (or a single pair, which
733
+ * is normalised to an array). Each pair is processed sequentially via
734
+ * `update()`, so each item gets its own filter validation, audit field
735
+ * transform, and cache invalidation.
736
+ *
737
+ * Returns all updated records across all pairs, flattened into a single
738
+ * array, each passed through `transformOnOut()`.
739
+ *
740
+ * Note: cache clearing is handled inside each `update()` call — there is
741
+ * no second pass over the results here.
742
+ */
352
743
  async updateMany(params) {
353
744
  if (!Array.isArray(params)) {
354
745
  params = [params];
@@ -359,22 +750,27 @@ class BaseGateway {
359
750
  const items = await this.update(item.where, item.params);
360
751
  results.push(...items);
361
752
  }
362
- if (results.length > 0 && this.config.noCache !== true) {
363
- const idName = this.getIdFieldUpdateRemove();
364
- results.forEach((item) => {
365
- if (item[idName]) {
366
- this.loader.clear(item[idName]);
367
- }
368
- });
369
- }
370
753
  return results.map((item) => this.transformOnOut(item));
371
754
  }
755
+ /**
756
+ * Increments numeric field(s) on records matching the `where` filter.
757
+ * Uses the database's native INCREMENT operation rather than a read-modify-write,
758
+ * making it safe for concurrent requests.
759
+ *
760
+ * `params` should be an object mapping field names to the increment amounts
761
+ * (e.g. `{ viewCount: 1 }`). `transformOnUpdate()` is still called, so
762
+ * audit fields (updatedAt, updatedBy) and version are updated as normal.
763
+ *
764
+ * Throws if no filter conditions are applied (same safety guard as `update()`).
765
+ * Clears affected records from the loader cache after the operation.
766
+ */
372
767
  async increment(where, params) {
373
768
  const object = await this.transformOnUpdate(params, where);
374
769
  const query = this.getBuilder().increment(object).returning(this.config.returnFields);
375
770
  const filtersAppliedQty = await this.onUpdateFilter(query, where);
376
771
  if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
377
- throw new Error(`Failed to update the table '${this.config.table}' as none of filters applied: ${JSON.stringify(where, null, 2)}`);
772
+ throw new Error(`Failed to increment in table '${this.config.table}': no filters applied. ` +
773
+ `Expected id field: '${this.getIdFieldUpdateRemove()}'. Received: ${JSON.stringify(where, null, 2)}`);
378
774
  }
379
775
  const items = await query;
380
776
  if (items.length > 0 && this.config.noCache !== true) {
@@ -387,12 +783,19 @@ class BaseGateway {
387
783
  }
388
784
  return items.map((item) => this.transformOnOut(item));
389
785
  }
786
+ /**
787
+ * Decrements numeric field(s) on records matching the `where` filter.
788
+ * Mirror of `increment()` using the database's native DECREMENT operation.
789
+ *
790
+ * Same behaviour, safety guards, and cache invalidation as `increment()`.
791
+ */
390
792
  async decrement(where, params) {
391
793
  const object = await this.transformOnUpdate(params, where);
392
794
  const query = this.getBuilder().decrement(object).returning(this.config.returnFields);
393
795
  const filtersAppliedQty = await this.onUpdateFilter(query, where);
394
796
  if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
395
- throw new Error(`Failed to update the table '${this.config.table}' as none of filters applied: ${JSON.stringify(where, null, 2)}`);
797
+ throw new Error(`Failed to decrement in table '${this.config.table}': no filters applied. ` +
798
+ `Expected id field: '${this.getIdFieldUpdateRemove()}'. Received: ${JSON.stringify(where, null, 2)}`);
396
799
  }
397
800
  const items = await query;
398
801
  if (items.length > 0 && this.config.noCache !== true) {
@@ -406,11 +809,29 @@ class BaseGateway {
406
809
  return items.map((item) => this.transformOnOut(item));
407
810
  }
408
811
  /**
409
- * Inserts or updates data in the database.
410
- * If the element of given array has not empty id field then the record is updated
411
- * oterwise inserted
412
- * @param params Array of objects to update or create
413
- * @returns Array of updated or inserted objects
812
+ * Upserts one or more records using INSERT ... ON CONFLICT ... MERGE.
813
+ *
814
+ * For each object:
815
+ * 1. Applies `transformOnSet()` (combined create + update transforms)
816
+ * 2. Generates an id if none is present
817
+ *
818
+ * The merge behaviour:
819
+ * - Conflict target: `config.setFields` if set, otherwise the id field
820
+ * - Fields merged on conflict: all keys found across all objects, minus
821
+ * `skipFields` (createdAt, createdBy, spaceId when their flags are set)
822
+ * - skipFields ensures that on conflict (update path), creation-time
823
+ * fields are not overwritten — existing records keep their original
824
+ * createdAt, createdBy, and spaceId values
825
+ * - If `config.mergeFields` is set, it takes precedence over the
826
+ * auto-derived field list entirely
827
+ *
828
+ * Inserts are batched into chunks of `config.insertChunkSize` (default 2500).
829
+ *
830
+ * Returns all upserted records (via RETURNING), each passed through
831
+ * `transformOnOut()`.
832
+ *
833
+ * Nuance: fields are collected from all objects (not just the first) to
834
+ * avoid silently dropping fields that only appear on some items in the batch.
414
835
  */
415
836
  async set(params) {
416
837
  const { hasCreatedAt, hasCreatedBy, hasSpace, mergeFields } = this.config || {};
@@ -419,15 +840,12 @@ class BaseGateway {
419
840
  return [];
420
841
  }
421
842
  const skipFields = [];
422
- if (hasCreatedAt) {
843
+ if (hasCreatedAt)
423
844
  skipFields.push(constants_1.FIELDS.CREATED_AT);
424
- }
425
- if (hasCreatedBy) {
845
+ if (hasCreatedBy)
426
846
  skipFields.push(constants_1.FIELDS.CREATED_BY);
427
- }
428
- if (hasSpace) {
847
+ if (hasSpace)
429
848
  skipFields.push(constants_1.FIELDS.SPACE_ID);
430
- }
431
849
  const idField = this.getIdFieldUpdateRemove();
432
850
  for (let idx = 0, len = objects.length; idx < len; ++idx) {
433
851
  const object = objects[idx];
@@ -436,7 +854,12 @@ class BaseGateway {
436
854
  objects[idx][idField] = await this.generateId(object);
437
855
  }
438
856
  }
439
- const fields = Array.isArray(mergeFields) ? mergeFields : Object.keys(objects[0]);
857
+ // Collect all unique keys across all objects to build the merge field list.
858
+ // Using only objects[0] would silently drop fields present on later items
859
+ // if the batch has inconsistent shapes.
860
+ const fields = Array.isArray(mergeFields)
861
+ ? mergeFields
862
+ : [...new Set(objects.flatMap((o) => Object.keys(o)))];
440
863
  const result = [];
441
864
  const chunks = (0, utils_1.arrToChunks)(objects, this.config?.insertChunkSize || DEFAULT_CHUNCK_SIZE);
442
865
  for (let idx = 0, len = chunks.length; idx < len; ++idx) {
@@ -449,6 +872,28 @@ class BaseGateway {
449
872
  }
450
873
  return result.map((item) => this.transformOnOut(item));
451
874
  }
875
+ /**
876
+ * Removes records matching the `where` filter, either hard or soft.
877
+ *
878
+ * Hard vs soft delete:
879
+ * - Hard delete (`hardRemove: true` OR `hasRemovedAt: false`):
880
+ * Issues a DELETE query. Records are permanently removed.
881
+ * - Soft delete (default when `hasRemovedAt: true`):
882
+ * Issues an UPDATE with the removal patch from `transformOnRemove()`.
883
+ * Records are retained in the database with removedAt, status = REMOVED,
884
+ * and optionally removedBy set.
885
+ *
886
+ * The `where` parameter is passed to both `onRemoveFilter()` (for the WHERE
887
+ * clause) and `transformOnRemove()` (so the removal patch can reference
888
+ * the filter, e.g. for lang/localisation key rotation).
889
+ *
890
+ * Throws if no filter conditions are applied — a safety guard to prevent
891
+ * an unfiltered DELETE or soft-delete UPDATE from affecting all rows.
892
+ *
893
+ * Clears affected records from the loader cache after the operation.
894
+ * Returns all affected records (via RETURNING), each passed through
895
+ * `transformOnOut()`.
896
+ */
452
897
  async remove(where) {
453
898
  const { hardRemove, hasRemovedAt } = this.config || {};
454
899
  const query = this.getBuilder();
@@ -456,12 +901,13 @@ class BaseGateway {
456
901
  query.delete(this.config.returnFields);
457
902
  }
458
903
  else {
459
- const object = await this.transformOnRemove();
904
+ const object = await this.transformOnRemove(where);
460
905
  query.update(object).returning(this.config.returnFields);
461
906
  }
462
907
  const filtersAppliedQty = await this.onRemoveFilter(query, where);
463
908
  if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
464
- throw new Error(`Failed to remove records in the table '${this.config.table}' as none of filters applied: ${JSON.stringify(where, null, 2)}`);
909
+ throw new Error(`Failed to remove records in table '${this.config.table}': no filters applied. ` +
910
+ `Expected id field: '${this.getIdFieldUpdateRemove()}'. Received: ${JSON.stringify(where, null, 2)}`);
465
911
  }
466
912
  const items = await query;
467
913
  if (items.length > 0 && this.config.noCache !== true) {