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