@sdflc/backend-helpers 1.0.122 → 1.0.123

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.
@@ -1,4 +1,3 @@
1
- // ./src/BaseGateway.ts
2
1
  import { v4 } from 'uuid';
3
2
  import dayjs from 'dayjs';
4
3
  import check from 'check-types';
@@ -7,6 +6,12 @@ import { arrToChunks, STATUSES, DateTimeHelpers, buildKey, Logger, LoggerLevels,
7
6
  import { DataCache } from './DataCache';
8
7
  import { FIELDS, ID_FIELD } from './constants';
9
8
  const DEFAULT_CHUNCK_SIZE = 2500;
9
+ /**
10
+ * Filter types that are valid on the update and remove paths.
11
+ * Search and date-range filters are intentionally excluded — update/remove
12
+ * filters must be precise identifiers, not fuzzy searches or time windows.
13
+ */
14
+ const UPDATE_REMOVE_SUPPORTED_TYPES = new Set(['array', 'eq', 'bool', 'nullableBool']);
10
15
  /**
11
16
  * BaseGateway is the foundation for all database-backed gateway classes.
12
17
  *
@@ -27,6 +32,25 @@ const DEFAULT_CHUNCK_SIZE = 2500;
27
32
  * attach computed properties)
28
33
  * - `generateId()` — to use a domain-specific ID strategy
29
34
  *
35
+ * ── Declarative filters ──────────────────────────────────────────────────────
36
+ * Simple, repetitive filter logic can be expressed via the listFilters,
37
+ * updateFilters, and removeFilters config arrays (see BaseGatewayPropsInterface).
38
+ * Rules are applied after the standard base logic inside onListFilter /
39
+ * onUpdateFilter / onRemoveFilter — they supplement, never replace, the
40
+ * override chain.
41
+ *
42
+ * ── Protected filter helpers ─────────────────────────────────────────────────
43
+ * Subclasses can call the following helpers directly inside their own
44
+ * onListFilter overrides instead of re-implementing the patterns themselves:
45
+ *
46
+ * applyArrayFilter(query, value, column)
47
+ * applyEqFilter(query, value, column)
48
+ * applyBoolFilter(query, value, column)
49
+ * applyNullableBoolFilter(query, value, column)
50
+ * applyDateRangeFilter(query, from, to, column)
51
+ * applyNullableDateRangeFilter(query, isNull, from, to, column)
52
+ * applySearchFilter(query, search, columns)
53
+ *
30
54
  * The loader (DataCache by default) is used for batched per-id loading
31
55
  * via DataLoader semantics. It is bypassed when `noCache: true` is set in
32
56
  * config, or when `list()` is called with `useCache: false`.
@@ -79,6 +103,7 @@ class BaseGateway {
79
103
  // for batched, per-request in-memory caching.
80
104
  this.loader = check.function(this.config?.loader) ? this.config.loader : new DataCache(this.config);
81
105
  }
106
+ // ─── Config / context accessors ────────────────────────────────────────────
82
107
  /**
83
108
  * Returns the full gateway config object.
84
109
  * Useful for subclasses or external code that needs to inspect configuration
@@ -124,6 +149,415 @@ class BaseGateway {
124
149
  this.loader = new DataCache({ ...this.config, ...config });
125
150
  return this;
126
151
  }
152
+ /**
153
+ * Returns the requestId from the current ApiContext.
154
+ * Useful for correlating log entries or error reports to a specific request.
155
+ */
156
+ getRequestId() {
157
+ return this.config.context.requestId;
158
+ }
159
+ /**
160
+ * Returns the full ApiContext associated with this gateway instance.
161
+ * The context carries request-scoped values: userId, spaceId, headers,
162
+ * other gateways, cores, db, etc.
163
+ */
164
+ getContext() {
165
+ return this.config.context;
166
+ }
167
+ /**
168
+ * Returns all gateway instances from the current request context.
169
+ * Allows one gateway to call another (e.g. UserGateway calling RoleGateway)
170
+ * without going through a core, using the same shared context and db connection.
171
+ *
172
+ * Returns an empty object if context is not available.
173
+ */
174
+ getGateways() {
175
+ return this.config.context?.gateways || {};
176
+ }
177
+ /**
178
+ * Returns the Database instance from config.
179
+ * All query builders are derived from this instance.
180
+ */
181
+ getDb() {
182
+ return this.config.db;
183
+ }
184
+ /**
185
+ * Returns a Knex query builder scoped to this gateway's table.
186
+ * The builder is a fresh instance each time — it does not carry state
187
+ * between calls.
188
+ */
189
+ getBuilder() {
190
+ return this.getDb()?.getBuilder(this.config.table);
191
+ }
192
+ /**
193
+ * Returns the primary key field name used for SELECT and loader operations.
194
+ * Defaults to the global ID_FIELD constant if not set in config.
195
+ *
196
+ * Note: this may differ from `getIdFieldUpdateRemove()` — some tables use
197
+ * a different column for update/delete filtering (e.g. a composite key)
198
+ * while listing and loading still uses the primary key.
199
+ */
200
+ getIdField() {
201
+ return this.config.idField || ID_FIELD;
202
+ }
203
+ /**
204
+ * Returns the field name used to identify records in UPDATE and DELETE
205
+ * WHERE clauses. Falls back through idFieldUpdateRemove → idField → ID_FIELD.
206
+ *
207
+ * Separate from `getIdField()` to support tables where the logical primary
208
+ * key used for loading differs from the column used for writes
209
+ * (e.g. a table with a UUID primary key but a separate "slug" as update target).
210
+ */
211
+ getIdFieldUpdateRemove() {
212
+ return this.config.idFieldUpdateRemove || this.config.idField || ID_FIELD;
213
+ }
214
+ // ─── Protected filter helpers ───────────────────────────────────────────────
215
+ //
216
+ // These helpers encode the common WHERE clause patterns used across gateway
217
+ // subclasses. Call them directly from onListFilter overrides to avoid
218
+ // re-implementing the same patterns in every gateway.
219
+ //
220
+ // All helpers are no-ops when the filter value is absent / null / undefined,
221
+ // so callers never need to guard against undefined before calling.
222
+ /**
223
+ * Applies a whereIn or where-equals filter for scalar or array values.
224
+ *
225
+ * Normalises the value to an array, discarding null / undefined / empty-string
226
+ * entries. Single-element arrays are unwrapped to a plain equality check so
227
+ * the query planner sees a simpler predicate.
228
+ *
229
+ * No-op when the normalised array is empty.
230
+ *
231
+ * @param query Knex query builder
232
+ * @param value Scalar value, array of values, null, or undefined
233
+ * @param column Fully-qualified column name (e.g. 'Party_Guest.Party_ID')
234
+ */
235
+ applyArrayFilter(query, value, column) {
236
+ const items = normaliseToArray(value);
237
+ if (items.length === 0)
238
+ return;
239
+ if (items.length === 1) {
240
+ query.where(column, items[0]);
241
+ }
242
+ else {
243
+ query.whereIn(column, items);
244
+ }
245
+ }
246
+ /**
247
+ * Applies a strict equality filter: WHERE column = value.
248
+ *
249
+ * No-op when value is null or undefined. Does NOT expand arrays —
250
+ * if the value might be an array, use applyArrayFilter instead.
251
+ *
252
+ * @param query Knex query builder
253
+ * @param value The exact value to match
254
+ * @param column Fully-qualified column name
255
+ */
256
+ applyEqFilter(query, value, column) {
257
+ if (value == null)
258
+ return;
259
+ query.where(column, value);
260
+ }
261
+ /**
262
+ * Applies a boolean equality filter: WHERE column = true/false.
263
+ *
264
+ * Only fires when value is strictly true or false. null, undefined, and
265
+ * any other type are ignored — the column is left unconstrained.
266
+ *
267
+ * Use for boolean columns where you want to filter on the stored value
268
+ * (e.g. WHERE Is_Starred = true). For nullable columns that encode
269
+ * presence via NULL / NOT NULL, use applyNullableBoolFilter instead.
270
+ *
271
+ * @param query Knex query builder
272
+ * @param value Must be strictly true or false to fire
273
+ * @param column Fully-qualified column name
274
+ */
275
+ applyBoolFilter(query, value, column) {
276
+ if (value === true || value === false) {
277
+ query.where(column, value);
278
+ }
279
+ }
280
+ /**
281
+ * Applies a null-presence filter driven by a boolean flag:
282
+ * true → WHERE column IS NOT NULL
283
+ * false → WHERE column IS NULL
284
+ * null / undefined → no-op (column is left unconstrained)
285
+ *
286
+ * Use when a nullable column encodes presence semantically — e.g.
287
+ * wasInvited ↔ Invited_At IS [NOT] NULL.
288
+ *
289
+ * @param query Knex query builder
290
+ * @param value true, false, null, or undefined
291
+ * @param column Fully-qualified column name
292
+ */
293
+ applyNullableBoolFilter(query, value, column) {
294
+ if (value === true) {
295
+ query.whereNotNull(column);
296
+ }
297
+ else if (value === false) {
298
+ query.whereNull(column);
299
+ }
300
+ // null / undefined: intentional no-op
301
+ }
302
+ /**
303
+ * Applies an inclusive date-range filter: WHERE column >= from AND column <= to.
304
+ *
305
+ * Each bound is independently optional — omitting one leaves that side open.
306
+ * Both bounds are no-ops when null or undefined.
307
+ *
308
+ * @param query Knex query builder
309
+ * @param from Inclusive lower bound (Date, ISO string, or null/undefined)
310
+ * @param to Inclusive upper bound (Date, ISO string, or null/undefined)
311
+ * @param column Fully-qualified column name
312
+ */
313
+ applyDateRangeFilter(query, from, to, column) {
314
+ if (from != null) {
315
+ query.where(column, '>=', from);
316
+ }
317
+ if (to != null) {
318
+ query.where(column, '<=', to);
319
+ }
320
+ }
321
+ /**
322
+ * Applies a composite nullable date-range filter combining a null-check phase
323
+ * and an optional from/to range, driven by three independent filter values.
324
+ *
325
+ * isNull controls the null-presence check:
326
+ * true → WHERE column IS NULL (from/to are skipped — meaningless on nulls)
327
+ * false → WHERE column IS NOT NULL, then from/to applied if present
328
+ * null / undefined → null-ness unconstrained; from/to applied if present
329
+ *
330
+ * This matches the pattern used across Party_Guest datetime columns (Rsvp_At,
331
+ * Checked_In_At, Checked_Out_At) where the consumer may want to find records
332
+ * with no timestamp, or records within a specific time window, or both.
333
+ *
334
+ * @param query Knex query builder
335
+ * @param isNull Boolean flag or null/undefined
336
+ * @param from Inclusive lower bound or null/undefined
337
+ * @param to Inclusive upper bound or null/undefined
338
+ * @param column Fully-qualified column name
339
+ */
340
+ applyNullableDateRangeFilter(query, isNull, from, to, column) {
341
+ if (isNull === true) {
342
+ query.whereNull(column);
343
+ // from/to are meaningless when forcing null — skip them
344
+ return;
345
+ }
346
+ if (isNull === false) {
347
+ query.whereNotNull(column);
348
+ }
349
+ this.applyDateRangeFilter(query, from, to, column);
350
+ }
351
+ /**
352
+ * Applies a case-insensitive LIKE / ILIKE search across one or more columns
353
+ * using OR semantics: WHERE (col1 LIKE %search% OR col2 LIKE %search% …).
354
+ *
355
+ * The operator ('like' vs 'ilike') is resolved from the connected database
356
+ * type via Database.getSqlLikeOperator():
357
+ * - PostgreSQL → 'ilike' (native case-insensitive LIKE)
358
+ * - MSSQL → 'like' (case-insensitive under _CI_ collations)
359
+ * - Others → 'like' (safe default)
360
+ *
361
+ * No-op when:
362
+ * - search is not a non-empty string after trimming
363
+ * - columns array is empty or not provided
364
+ * - the Database instance is unavailable
365
+ *
366
+ * @param query Knex query builder
367
+ * @param search The search string (will be wrapped in %)
368
+ * @param columns One or more fully-qualified column names to search across
369
+ */
370
+ applySearchFilter(query, search, columns) {
371
+ if (!Array.isArray(columns) || columns.length === 0)
372
+ return;
373
+ const term = typeof search === 'string' ? search.trim() : '';
374
+ if (term.length === 0)
375
+ return;
376
+ const likeOp = this.getDb()?.getSqlLikeOperator() ?? 'like';
377
+ const pattern = `%${term}%`;
378
+ query.where((sub) => {
379
+ columns.forEach((col, idx) => {
380
+ if (idx === 0) {
381
+ sub.where(col, likeOp, pattern);
382
+ }
383
+ else {
384
+ sub.orWhere(col, likeOp, pattern);
385
+ }
386
+ });
387
+ });
388
+ }
389
+ // ─── Declarative filter application ────────────────────────────────────────
390
+ /**
391
+ * Applies a single GatewayFilterRule to a Knex query builder against
392
+ * the provided filter params object.
393
+ *
394
+ * Called by applyDeclarativeListFilters and is also available to subclasses
395
+ * that want to apply individual rules from custom filter methods.
396
+ *
397
+ * Returns true if the rule produced at least one WHERE clause,
398
+ * false if it was a no-op (value absent, unsupported type, etc.).
399
+ *
400
+ * Note: for 'dateRange' and 'nullableDateRange' the return value reflects
401
+ * whether the rule was structurally valid, not whether any bound was
402
+ * actually present (since both bounds are optional).
403
+ */
404
+ applyFilterRule(query, rule, filterParams) {
405
+ const { field, column, type, columns } = rule;
406
+ const value = filterParams?.[field];
407
+ switch (type) {
408
+ case 'array': {
409
+ const items = normaliseToArray(value);
410
+ if (items.length === 0)
411
+ return false;
412
+ this.applyArrayFilter(query, value, column);
413
+ return true;
414
+ }
415
+ case 'eq': {
416
+ if (value == null)
417
+ return false;
418
+ this.applyEqFilter(query, value, column);
419
+ return true;
420
+ }
421
+ case 'bool': {
422
+ if (value !== true && value !== false)
423
+ return false;
424
+ this.applyBoolFilter(query, value, column);
425
+ return true;
426
+ }
427
+ case 'nullableBool': {
428
+ if (value !== true && value !== false)
429
+ return false;
430
+ this.applyNullableBoolFilter(query, value, column);
431
+ return true;
432
+ }
433
+ case 'dateRange': {
434
+ const from = filterParams?.[`${field}From`];
435
+ const to = filterParams?.[`${field}To`];
436
+ this.applyDateRangeFilter(query, from, to, column);
437
+ // Counts as applied when at least one bound is present
438
+ return from != null || to != null;
439
+ }
440
+ case 'nullableDateRange': {
441
+ const isNull = filterParams?.[`${field}Null`];
442
+ const from = filterParams?.[`${field}From`];
443
+ const to = filterParams?.[`${field}To`];
444
+ this.applyNullableDateRangeFilter(query, isNull, from, to, column);
445
+ return isNull != null || from != null || to != null;
446
+ }
447
+ case 'search': {
448
+ const term = typeof value === 'string' ? value.trim() : '';
449
+ if (term.length === 0 || !Array.isArray(columns) || columns.length === 0)
450
+ return false;
451
+ this.applySearchFilter(query, value, columns);
452
+ return true;
453
+ }
454
+ default: {
455
+ // Exhaustiveness guard — TypeScript narrows 'never' here if all cases
456
+ // are covered, so this branch fires only when an unknown type is passed
457
+ // at runtime (e.g. via a cast or a future type added without updating
458
+ // this switch).
459
+ this.logger.log(`BaseGateway: skipping filter rule with unrecognised type "${rule.type}" for field "${field}"`);
460
+ return false;
461
+ }
462
+ }
463
+ }
464
+ /**
465
+ * Applies all rules from config.listFilters to the query in declaration order.
466
+ * Called at the end of onListFilter() after the standard base logic.
467
+ *
468
+ * All filter types are supported on the list path.
469
+ */
470
+ applyDeclarativeListFilters(query, filterParams) {
471
+ const rules = this.config.listFilters;
472
+ if (!Array.isArray(rules) || rules.length === 0)
473
+ return;
474
+ for (const rule of rules) {
475
+ this.applyFilterRule(query, rule, filterParams);
476
+ }
477
+ }
478
+ /**
479
+ * Applies all rules from config.updateFilters to the query in declaration order.
480
+ * Called at the end of onUpdateFilter() after the standard base logic.
481
+ *
482
+ * Returns the count of rules that actually produced a WHERE clause,
483
+ * which is added to filtersAppliedQty in the caller.
484
+ *
485
+ * 'search', 'dateRange', and 'nullableDateRange' are not valid on the update
486
+ * path — they are skipped with a warning log.
487
+ */
488
+ applyDeclarativeUpdateFilters(query, filterParams) {
489
+ const rules = this.config.updateFilters;
490
+ if (!Array.isArray(rules) || rules.length === 0)
491
+ return 0;
492
+ let count = 0;
493
+ for (const rule of rules) {
494
+ if (!UPDATE_REMOVE_SUPPORTED_TYPES.has(rule.type)) {
495
+ this.logger.log(`BaseGateway: update filter rule for field "${rule.field}" has unsupported type "${rule.type}" — skipped. ` +
496
+ `Only 'array', 'eq', 'bool', 'nullableBool' are supported on the update path.`);
497
+ continue;
498
+ }
499
+ if (this.applyFilterRule(query, rule, filterParams)) {
500
+ count++;
501
+ }
502
+ }
503
+ return count;
504
+ }
505
+ /**
506
+ * Applies all rules from config.removeFilters to the query in declaration order.
507
+ * Called at the end of onRemoveFilter() after the standard base logic.
508
+ *
509
+ * The remove path operates on castArray(whereParams) — a potentially multi-
510
+ * entry array for bulk removes. For 'array' type rules, values are collected
511
+ * across ALL entries and applied as a single whereIn, consistent with the
512
+ * bulk-remove pattern in PartyGuestGw.onRemoveFilter.
513
+ *
514
+ * For non-array types (eq, bool, nullableBool), only the first entry's value
515
+ * is used, since these filters express single-value constraints that cannot
516
+ * meaningfully be merged across multiple remove targets.
517
+ *
518
+ * Returns the count of rules that actually produced a WHERE clause.
519
+ *
520
+ * 'search', 'dateRange', and 'nullableDateRange' are not valid on the remove
521
+ * path — they are skipped with a warning log.
522
+ */
523
+ applyDeclarativeRemoveFilters(query, whereParams) {
524
+ const rules = this.config.removeFilters;
525
+ if (!Array.isArray(rules) || rules.length === 0)
526
+ return 0;
527
+ const entries = castArray(whereParams).filter(Boolean);
528
+ let count = 0;
529
+ for (const rule of rules) {
530
+ if (!UPDATE_REMOVE_SUPPORTED_TYPES.has(rule.type)) {
531
+ this.logger.log(`BaseGateway: remove filter rule for field "${rule.field}" has unsupported type "${rule.type}" — skipped. ` +
532
+ `Only 'array', 'eq', 'bool', 'nullableBool' are supported on the remove path.`);
533
+ continue;
534
+ }
535
+ if (rule.type === 'array') {
536
+ // Collect values across all entries for bulk-remove support
537
+ const allValues = [
538
+ ...new Set(entries.flatMap((entry) => normaliseToArray(entry?.[rule.field])).filter((v) => v != null && v !== '')),
539
+ ];
540
+ if (allValues.length === 0)
541
+ continue;
542
+ if (allValues.length === 1) {
543
+ query.where(rule.column, allValues[0]);
544
+ }
545
+ else {
546
+ query.whereIn(rule.column, allValues);
547
+ }
548
+ count++;
549
+ }
550
+ else {
551
+ // For non-array types use only the first entry's value
552
+ const firstParams = entries[0] ?? {};
553
+ if (this.applyFilterRule(query, rule, firstParams)) {
554
+ count++;
555
+ }
556
+ }
557
+ }
558
+ return count;
559
+ }
560
+ // ─── ID generation ─────────────────────────────────────────────────────────
127
561
  /**
128
562
  * Generates a unique ID for a new record.
129
563
  *
@@ -136,13 +570,15 @@ class BaseGateway {
136
570
  async generateId(_object) {
137
571
  return v4();
138
572
  }
573
+ // ─── Filter hooks ──────────────────────────────────────────────────────────
139
574
  /**
140
575
  * Applies WHERE clauses to a list query based on the provided filter params.
141
576
  * Called internally by `list()` after the base query is built.
142
577
  *
143
578
  * Override in subclasses to add resource-specific filters. Always call
144
579
  * `super.onListFilter(query, filterParams)` first to preserve the standard
145
- * filtering behaviour (status, spaceId, lang, keyword, etc.).
580
+ * filtering behaviour (status, spaceId, lang, keyword, etc.) AND to ensure
581
+ * declarative listFilters rules are applied.
146
582
  *
147
583
  * Built-in filter behaviours (each controlled by a config flag):
148
584
  * - `hasStatus` — filters by status; defaults to activeStatuses if
@@ -152,6 +588,7 @@ class BaseGateway {
152
588
  * - `hasLang` — filters by language
153
589
  * - `fieldForKeyword` — applies a case-insensitive LIKE on the configured field
154
590
  * - `filterByUserField` — scopes to the current userId from context
591
+ * - `listFilters` — applies declarative GatewayFilterRule array (new)
155
592
  *
156
593
  * Nuance: `hasSpace` checks both `filterParams[SPACE_ID]` and
157
594
  * `context.spaceId`, preferring the explicit param. If neither is set and
@@ -185,6 +622,9 @@ class BaseGateway {
185
622
  if (filterByUserField) {
186
623
  query.where({ [filterByUserField]: this.getContext()?.userId });
187
624
  }
625
+ // Declarative list filter rules — applied last so subclass super() calls
626
+ // are unaffected and custom overrides always run before declarative rules.
627
+ this.applyDeclarativeListFilters(query, filterParams);
188
628
  }
189
629
  /**
190
630
  * Applies WHERE clauses to an update query based on the provided filter params.
@@ -201,6 +641,7 @@ class BaseGateway {
201
641
  * - `hasVersion` — adds an optimistic-lock check on the version field,
202
642
  * preventing updates if the version has changed since the record was read
203
643
  * - `hasStatus` — excludes already-removed records from being updated
644
+ * - `updateFilters` — applies declarative GatewayFilterRule array (new)
204
645
  */
205
646
  async onUpdateFilter(query, filterParams) {
206
647
  const { hasStatus, hasVersion } = this.config;
@@ -225,6 +666,8 @@ class BaseGateway {
225
666
  query.where(FIELDS.STATUS, '!=', STATUSES.REMOVED);
226
667
  }
227
668
  }
669
+ // Declarative update filter rules — applied after base logic.
670
+ filtersAppliedQty += this.applyDeclarativeUpdateFilters(query, filterParams);
228
671
  return filtersAppliedQty;
229
672
  }
230
673
  /**
@@ -243,6 +686,7 @@ class BaseGateway {
243
686
  * Built-in filter behaviours:
244
687
  * - Collects the id field (idFieldUpdateRemove) from each item in filterParams
245
688
  * - `hasStatus` — adds a guard to prevent double-removal of already-removed records
689
+ * - `removeFilters` — applies declarative GatewayFilterRule array (new)
246
690
  */
247
691
  async onRemoveFilter(query, filterParams) {
248
692
  const { hasStatus } = this.config;
@@ -263,8 +707,11 @@ class BaseGateway {
263
707
  filtersAppliedQty++;
264
708
  query.where(FIELDS.STATUS, '!=', STATUSES.REMOVED);
265
709
  }
710
+ // Declarative remove filter rules — applied after base logic.
711
+ filtersAppliedQty += this.applyDeclarativeRemoveFilters(query, filterParams);
266
712
  return filtersAppliedQty;
267
713
  }
714
+ // ─── Record transforms ─────────────────────────────────────────────────────
268
715
  /**
269
716
  * Transforms a params object before it is inserted into the database.
270
717
  * Called once per object inside the `create()` loop, after the ID is generated.
@@ -502,68 +949,7 @@ class BaseGateway {
502
949
  transformOnOut(item) {
503
950
  return item;
504
951
  }
505
- /**
506
- * Returns the requestId from the current ApiContext.
507
- * Useful for correlating log entries or error reports to a specific request.
508
- */
509
- getRequestId() {
510
- return this.config.context.requestId;
511
- }
512
- /**
513
- * Returns the full ApiContext associated with this gateway instance.
514
- * The context carries request-scoped values: userId, spaceId, headers,
515
- * other gateways, cores, db, etc.
516
- */
517
- getContext() {
518
- return this.config.context;
519
- }
520
- /**
521
- * Returns all gateway instances from the current request context.
522
- * Allows one gateway to call another (e.g. UserGateway calling RoleGateway)
523
- * without going through a core, using the same shared context and db connection.
524
- *
525
- * Returns an empty object if context is not available.
526
- */
527
- getGateways() {
528
- return this.config.context?.gateways || {};
529
- }
530
- /**
531
- * Returns the Database instance from config.
532
- * All query builders are derived from this instance.
533
- */
534
- getDb() {
535
- return this.config.db;
536
- }
537
- /**
538
- * Returns a Knex query builder scoped to this gateway's table.
539
- * The builder is a fresh instance each time — it does not carry state
540
- * between calls.
541
- */
542
- getBuilder() {
543
- return this.getDb()?.getBuilder(this.config.table);
544
- }
545
- /**
546
- * Returns the primary key field name used for SELECT and loader operations.
547
- * Defaults to the global ID_FIELD constant if not set in config.
548
- *
549
- * Note: this may differ from `getIdFieldUpdateRemove()` — some tables use
550
- * a different column for update/delete filtering (e.g. a composite key)
551
- * while listing and loading still uses the primary key.
552
- */
553
- getIdField() {
554
- return this.config.idField || ID_FIELD;
555
- }
556
- /**
557
- * Returns the field name used to identify records in UPDATE and DELETE
558
- * WHERE clauses. Falls back through idFieldUpdateRemove → idField → ID_FIELD.
559
- *
560
- * Separate from `getIdField()` to support tables where the logical primary
561
- * key used for loading differs from the column used for writes
562
- * (e.g. a table with a UUID primary key but a separate "slug" as update target).
563
- */
564
- getIdFieldUpdateRemove() {
565
- return this.config.idFieldUpdateRemove || this.config.idField || ID_FIELD;
566
- }
952
+ // ─── Loader operations ─────────────────────────────────────────────────────
567
953
  /**
568
954
  * Loads a single record by id via the loader (DataCache/DataLoader).
569
955
  * Leverages DataLoader batching — multiple `get()` calls within the same
@@ -586,6 +972,7 @@ class BaseGateway {
586
972
  async getMany(ids) {
587
973
  return this.loader.loadMany(ids);
588
974
  }
975
+ // ─── Query building ────────────────────────────────────────────────────────
589
976
  /**
590
977
  * Builds the base SELECT query for `list()`.
591
978
  * Override in subclasses to add JOINs, computed columns, or subqueries
@@ -606,6 +993,7 @@ class BaseGateway {
606
993
  query.select(fieldsToUse || '*');
607
994
  return { query };
608
995
  }
996
+ // ─── CRUD operations ───────────────────────────────────────────────────────
609
997
  /**
610
998
  * Fetches a paginated, filtered list of records from the database.
611
999
  *
@@ -918,3 +1306,22 @@ class BaseGateway {
918
1306
  }
919
1307
  }
920
1308
  export { BaseGateway };
1309
+ // ─── Module-level helpers ──────────────────────────────────────────────────────
1310
+ /**
1311
+ * Normalises a scalar or array value into a non-empty any[].
1312
+ *
1313
+ * Rules:
1314
+ * - null / undefined → []
1315
+ * - '' (empty string) → []
1316
+ * - scalar → [scalar]
1317
+ * - array → filtered to remove null / undefined / '' entries
1318
+ *
1319
+ * Kept module-private — callers use the protected gateway methods instead.
1320
+ * Not exported because nothing outside this file needs direct access.
1321
+ */
1322
+ function normaliseToArray(value) {
1323
+ if (value == null)
1324
+ return [];
1325
+ const arr = Array.isArray(value) ? value : [value];
1326
+ return arr.filter((v) => v != null && v !== '');
1327
+ }
@@ -41,6 +41,21 @@ declare class Database {
41
41
  * DB error message directly or log it and return a generic message.
42
42
  */
43
43
  isDbError(ex: any): [boolean, string];
44
+ /**
45
+ * Returns the SQL LIKE operator appropriate for the connected database engine.
46
+ *
47
+ * PostgreSQL supports ILIKE natively — a case-insensitive variant of LIKE.
48
+ * MS Azure SQL Server and MySQL do not have ILIKE; they use plain LIKE, which
49
+ * is case-insensitive by default under the collations used in this project
50
+ * (e.g. SQL_Latin1_General_CP1_CI_AS on MSSQL, utf8_general_ci on MySQL).
51
+ *
52
+ * Use this wherever a case-insensitive pattern match is needed so the
53
+ * correct operator is chosen automatically without branching in gateway code.
54
+ *
55
+ * Knex client strings: 'pg' | 'pg-native' for PostgreSQL; 'mssql' | 'tedious'
56
+ * for SQL Server; 'mysql' | 'mysql2' for MySQL.
57
+ */
58
+ getSqlLikeOperator(): string;
44
59
  /**
45
60
  * Creates a new Knex transaction.
46
61
  * If `trx` is provided, creates a nested transaction on the existing one.