@sdflc/backend-helpers 1.0.122 → 1.0.124

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.
@@ -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.
package/build/Database.js CHANGED
@@ -1,5 +1,4 @@
1
1
  "use strict";
2
- // ./src/Database.ts (capitalised to match class name convention)
3
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
4
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
4
  };
@@ -106,6 +105,23 @@ class Database {
106
105
  return [false, ''];
107
106
  }
108
107
  }
108
+ /**
109
+ * Returns the SQL LIKE operator appropriate for the connected database engine.
110
+ *
111
+ * PostgreSQL supports ILIKE natively — a case-insensitive variant of LIKE.
112
+ * MS Azure SQL Server and MySQL do not have ILIKE; they use plain LIKE, which
113
+ * is case-insensitive by default under the collations used in this project
114
+ * (e.g. SQL_Latin1_General_CP1_CI_AS on MSSQL, utf8_general_ci on MySQL).
115
+ *
116
+ * Use this wherever a case-insensitive pattern match is needed so the
117
+ * correct operator is chosen automatically without branching in gateway code.
118
+ *
119
+ * Knex client strings: 'pg' | 'pg-native' for PostgreSQL; 'mssql' | 'tedious'
120
+ * for SQL Server; 'mysql' | 'mysql2' for MySQL.
121
+ */
122
+ getSqlLikeOperator() {
123
+ return this.dbType === 'pg' || this.dbType === 'pg-native' ? 'ilike' : 'like';
124
+ }
109
125
  /**
110
126
  * Creates a new Knex transaction.
111
127
  * If `trx` is provided, creates a nested transaction on the existing one.
@@ -1,6 +1,6 @@
1
1
  import { DateTimeHelpers, Logger } from '@sdflc/utils';
2
2
  import { DataCache } from './DataCache';
3
- import { ApiContext, BaseGatewayPropsInterface, BuildListQueryArgsInterface, CacheInterface, ListArgsInterface, LoaderInterface } from './interfaces';
3
+ import { ApiContext, BaseGatewayPropsInterface, BuildListQueryArgsInterface, CacheInterface, GatewayFilterRule, ListArgsInterface, LoaderInterface } from './interfaces';
4
4
  import { Database } from './Database';
5
5
  /**
6
6
  * BaseGateway is the foundation for all database-backed gateway classes.
@@ -22,6 +22,25 @@ import { Database } from './Database';
22
22
  * attach computed properties)
23
23
  * - `generateId()` — to use a domain-specific ID strategy
24
24
  *
25
+ * ── Declarative filters ──────────────────────────────────────────────────────
26
+ * Simple, repetitive filter logic can be expressed via the listFilters,
27
+ * updateFilters, and removeFilters config arrays (see BaseGatewayPropsInterface).
28
+ * Rules are applied after the standard base logic inside onListFilter /
29
+ * onUpdateFilter / onRemoveFilter — they supplement, never replace, the
30
+ * override chain.
31
+ *
32
+ * ── Protected filter helpers ─────────────────────────────────────────────────
33
+ * Subclasses can call the following helpers directly inside their own
34
+ * onListFilter overrides instead of re-implementing the patterns themselves:
35
+ *
36
+ * applyArrayFilter(query, value, column)
37
+ * applyEqFilter(query, value, column)
38
+ * applyBoolFilter(query, value, column)
39
+ * applyNullableBoolFilter(query, value, column)
40
+ * applyDateRangeFilter(query, from, to, column)
41
+ * applyNullableDateRangeFilter(query, isNull, from, to, column)
42
+ * applySearchFilter(query, search, columns)
43
+ *
25
44
  * The loader (DataCache by default) is used for batched per-id loading
26
45
  * via DataLoader semantics. It is bypassed when `noCache: true` is set in
27
46
  * config, or when `list()` is called with `useCache: false`.
@@ -76,6 +95,212 @@ declare class BaseGateway {
76
95
  * Returns `this` for chaining.
77
96
  */
78
97
  setLoaderConfig(config: CacheInterface): this;
98
+ /**
99
+ * Returns the requestId from the current ApiContext.
100
+ * Useful for correlating log entries or error reports to a specific request.
101
+ */
102
+ getRequestId(): string;
103
+ /**
104
+ * Returns the full ApiContext associated with this gateway instance.
105
+ * The context carries request-scoped values: userId, spaceId, headers,
106
+ * other gateways, cores, db, etc.
107
+ */
108
+ getContext(): ApiContext;
109
+ /**
110
+ * Returns all gateway instances from the current request context.
111
+ * Allows one gateway to call another (e.g. UserGateway calling RoleGateway)
112
+ * without going through a core, using the same shared context and db connection.
113
+ *
114
+ * Returns an empty object if context is not available.
115
+ */
116
+ getGateways(): Record<string, any>;
117
+ /**
118
+ * Returns the Database instance from config.
119
+ * All query builders are derived from this instance.
120
+ */
121
+ getDb(): Database | undefined;
122
+ /**
123
+ * Returns a Knex query builder scoped to this gateway's table.
124
+ * The builder is a fresh instance each time — it does not carry state
125
+ * between calls.
126
+ */
127
+ getBuilder(): any;
128
+ /**
129
+ * Returns the primary key field name used for SELECT and loader operations.
130
+ * Defaults to the global ID_FIELD constant if not set in config.
131
+ *
132
+ * Note: this may differ from `getIdFieldUpdateRemove()` — some tables use
133
+ * a different column for update/delete filtering (e.g. a composite key)
134
+ * while listing and loading still uses the primary key.
135
+ */
136
+ getIdField(): string;
137
+ /**
138
+ * Returns the field name used to identify records in UPDATE and DELETE
139
+ * WHERE clauses. Falls back through idFieldUpdateRemove → idField → ID_FIELD.
140
+ *
141
+ * Separate from `getIdField()` to support tables where the logical primary
142
+ * key used for loading differs from the column used for writes
143
+ * (e.g. a table with a UUID primary key but a separate "slug" as update target).
144
+ */
145
+ getIdFieldUpdateRemove(): string;
146
+ /**
147
+ * Applies a whereIn or where-equals filter for scalar or array values.
148
+ *
149
+ * Normalises the value to an array, discarding null / undefined / empty-string
150
+ * entries. Single-element arrays are unwrapped to a plain equality check so
151
+ * the query planner sees a simpler predicate.
152
+ *
153
+ * No-op when the normalised array is empty.
154
+ *
155
+ * @param query Knex query builder
156
+ * @param value Scalar value, array of values, null, or undefined
157
+ * @param column Fully-qualified column name (e.g. 'Party_Guest.Party_ID')
158
+ */
159
+ protected applyArrayFilter(query: any, value: any, column: string): void;
160
+ /**
161
+ * Applies a strict equality filter: WHERE column = value.
162
+ *
163
+ * No-op when value is null or undefined. Does NOT expand arrays —
164
+ * if the value might be an array, use applyArrayFilter instead.
165
+ *
166
+ * @param query Knex query builder
167
+ * @param value The exact value to match
168
+ * @param column Fully-qualified column name
169
+ */
170
+ protected applyEqFilter(query: any, value: any, column: string): void;
171
+ /**
172
+ * Applies a boolean equality filter: WHERE column = true/false.
173
+ *
174
+ * Only fires when value is strictly true or false. null, undefined, and
175
+ * any other type are ignored — the column is left unconstrained.
176
+ *
177
+ * Use for boolean columns where you want to filter on the stored value
178
+ * (e.g. WHERE Is_Starred = true). For nullable columns that encode
179
+ * presence via NULL / NOT NULL, use applyNullableBoolFilter instead.
180
+ *
181
+ * @param query Knex query builder
182
+ * @param value Must be strictly true or false to fire
183
+ * @param column Fully-qualified column name
184
+ */
185
+ protected applyBoolFilter(query: any, value: any, column: string): void;
186
+ /**
187
+ * Applies a null-presence filter driven by a boolean flag:
188
+ * true → WHERE column IS NOT NULL
189
+ * false → WHERE column IS NULL
190
+ * null / undefined → no-op (column is left unconstrained)
191
+ *
192
+ * Use when a nullable column encodes presence semantically — e.g.
193
+ * wasInvited ↔ Invited_At IS [NOT] NULL.
194
+ *
195
+ * @param query Knex query builder
196
+ * @param value true, false, null, or undefined
197
+ * @param column Fully-qualified column name
198
+ */
199
+ protected applyNullableBoolFilter(query: any, value: any, column: string): void;
200
+ /**
201
+ * Applies an inclusive date-range filter: WHERE column >= from AND column <= to.
202
+ *
203
+ * Each bound is independently optional — omitting one leaves that side open.
204
+ * Both bounds are no-ops when null or undefined.
205
+ *
206
+ * @param query Knex query builder
207
+ * @param from Inclusive lower bound (Date, ISO string, or null/undefined)
208
+ * @param to Inclusive upper bound (Date, ISO string, or null/undefined)
209
+ * @param column Fully-qualified column name
210
+ */
211
+ protected applyDateRangeFilter(query: any, from: Date | string | undefined | null, to: Date | string | undefined | null, column: string): void;
212
+ /**
213
+ * Applies a composite nullable date-range filter combining a null-check phase
214
+ * and an optional from/to range, driven by three independent filter values.
215
+ *
216
+ * isNull controls the null-presence check:
217
+ * true → WHERE column IS NULL (from/to are skipped — meaningless on nulls)
218
+ * false → WHERE column IS NOT NULL, then from/to applied if present
219
+ * null / undefined → null-ness unconstrained; from/to applied if present
220
+ *
221
+ * This matches the pattern used across Party_Guest datetime columns (Rsvp_At,
222
+ * Checked_In_At, Checked_Out_At) where the consumer may want to find records
223
+ * with no timestamp, or records within a specific time window, or both.
224
+ *
225
+ * @param query Knex query builder
226
+ * @param isNull Boolean flag or null/undefined
227
+ * @param from Inclusive lower bound or null/undefined
228
+ * @param to Inclusive upper bound or null/undefined
229
+ * @param column Fully-qualified column name
230
+ */
231
+ protected applyNullableDateRangeFilter(query: any, isNull: boolean | undefined | null, from: Date | string | undefined | null, to: Date | string | undefined | null, column: string): void;
232
+ /**
233
+ * Applies a case-insensitive LIKE / ILIKE search across one or more columns
234
+ * using OR semantics: WHERE (col1 LIKE %search% OR col2 LIKE %search% …).
235
+ *
236
+ * The operator ('like' vs 'ilike') is resolved from the connected database
237
+ * type via Database.getSqlLikeOperator():
238
+ * - PostgreSQL → 'ilike' (native case-insensitive LIKE)
239
+ * - MSSQL → 'like' (case-insensitive under _CI_ collations)
240
+ * - Others → 'like' (safe default)
241
+ *
242
+ * No-op when:
243
+ * - search is not a non-empty string after trimming
244
+ * - columns array is empty or not provided
245
+ * - the Database instance is unavailable
246
+ *
247
+ * @param query Knex query builder
248
+ * @param search The search string (will be wrapped in %)
249
+ * @param columns One or more fully-qualified column names to search across
250
+ */
251
+ protected applySearchFilter(query: any, search: any, columns: string[]): void;
252
+ /**
253
+ * Applies a single GatewayFilterRule to a Knex query builder against
254
+ * the provided filter params object.
255
+ *
256
+ * Called by applyDeclarativeListFilters and is also available to subclasses
257
+ * that want to apply individual rules from custom filter methods.
258
+ *
259
+ * Returns true if the rule produced at least one WHERE clause,
260
+ * false if it was a no-op (value absent, unsupported type, etc.).
261
+ *
262
+ * Note: for 'dateRange' and 'nullableDateRange' the return value reflects
263
+ * whether the rule was structurally valid, not whether any bound was
264
+ * actually present (since both bounds are optional).
265
+ */
266
+ protected applyFilterRule(query: any, rule: GatewayFilterRule, filterParams: any): boolean;
267
+ /**
268
+ * Applies all rules from config.listFilters to the query in declaration order.
269
+ * Called at the end of onListFilter() after the standard base logic.
270
+ *
271
+ * All filter types are supported on the list path.
272
+ */
273
+ private applyDeclarativeListFilters;
274
+ /**
275
+ * Applies all rules from config.updateFilters to the query in declaration order.
276
+ * Called at the end of onUpdateFilter() after the standard base logic.
277
+ *
278
+ * Returns the count of rules that actually produced a WHERE clause,
279
+ * which is added to filtersAppliedQty in the caller.
280
+ *
281
+ * 'search', 'dateRange', and 'nullableDateRange' are not valid on the update
282
+ * path — they are skipped with a warning log.
283
+ */
284
+ private applyDeclarativeUpdateFilters;
285
+ /**
286
+ * Applies all rules from config.removeFilters to the query in declaration order.
287
+ * Called at the end of onRemoveFilter() after the standard base logic.
288
+ *
289
+ * The remove path operates on castArray(whereParams) — a potentially multi-
290
+ * entry array for bulk removes. For 'array' type rules, values are collected
291
+ * across ALL entries and applied as a single whereIn, consistent with the
292
+ * bulk-remove pattern in PartyGuestGw.onRemoveFilter.
293
+ *
294
+ * For non-array types (eq, bool, nullableBool), only the first entry's value
295
+ * is used, since these filters express single-value constraints that cannot
296
+ * meaningfully be merged across multiple remove targets.
297
+ *
298
+ * Returns the count of rules that actually produced a WHERE clause.
299
+ *
300
+ * 'search', 'dateRange', and 'nullableDateRange' are not valid on the remove
301
+ * path — they are skipped with a warning log.
302
+ */
303
+ private applyDeclarativeRemoveFilters;
79
304
  /**
80
305
  * Generates a unique ID for a new record.
81
306
  *
@@ -92,7 +317,8 @@ declare class BaseGateway {
92
317
  *
93
318
  * Override in subclasses to add resource-specific filters. Always call
94
319
  * `super.onListFilter(query, filterParams)` first to preserve the standard
95
- * filtering behaviour (status, spaceId, lang, keyword, etc.).
320
+ * filtering behaviour (status, spaceId, lang, keyword, etc.) AND to ensure
321
+ * declarative listFilters rules are applied.
96
322
  *
97
323
  * Built-in filter behaviours (each controlled by a config flag):
98
324
  * - `hasStatus` — filters by status; defaults to activeStatuses if
@@ -102,6 +328,7 @@ declare class BaseGateway {
102
328
  * - `hasLang` — filters by language
103
329
  * - `fieldForKeyword` — applies a case-insensitive LIKE on the configured field
104
330
  * - `filterByUserField` — scopes to the current userId from context
331
+ * - `listFilters` — applies declarative GatewayFilterRule array (new)
105
332
  *
106
333
  * Nuance: `hasSpace` checks both `filterParams[SPACE_ID]` and
107
334
  * `context.spaceId`, preferring the explicit param. If neither is set and
@@ -123,6 +350,7 @@ declare class BaseGateway {
123
350
  * - `hasVersion` — adds an optimistic-lock check on the version field,
124
351
  * preventing updates if the version has changed since the record was read
125
352
  * - `hasStatus` — excludes already-removed records from being updated
353
+ * - `updateFilters` — applies declarative GatewayFilterRule array (new)
126
354
  */
127
355
  onUpdateFilter(query: any, filterParams: any): Promise<number>;
128
356
  /**
@@ -141,8 +369,23 @@ declare class BaseGateway {
141
369
  * Built-in filter behaviours:
142
370
  * - Collects the id field (idFieldUpdateRemove) from each item in filterParams
143
371
  * - `hasStatus` — adds a guard to prevent double-removal of already-removed records
372
+ * - `removeFilters` — applies declarative GatewayFilterRule array (new)
144
373
  */
145
374
  onRemoveFilter(query: any, filterParams: any): Promise<number>;
375
+ /**
376
+ * Hook called by count() to apply custom WHERE conditions to the count query.
377
+ *
378
+ * Parallel to onListFilter() — override in subclasses that need filter logic
379
+ * beyond what the declarative countFilters rules can express (OR conditions,
380
+ * subqueries, cross-table joins, etc.).
381
+ *
382
+ * The base implementation is a no-op. Call super.onCountFilter() when
383
+ * overriding so future base-class logic is not silently skipped.
384
+ *
385
+ * @param query Knex query builder for the count query
386
+ * @param filterParams The raw filter object passed to count()
387
+ */
388
+ protected onCountFilter(query: any, filterParams: any): void;
146
389
  /**
147
390
  * Transforms a params object before it is inserted into the database.
148
391
  * Called once per object inside the `create()` loop, after the ID is generated.
@@ -262,54 +505,6 @@ declare class BaseGateway {
262
505
  * must be handled in the loader's priming logic or in the calling code.
263
506
  */
264
507
  protected transformOnOut(item: any): any;
265
- /**
266
- * Returns the requestId from the current ApiContext.
267
- * Useful for correlating log entries or error reports to a specific request.
268
- */
269
- getRequestId(): string;
270
- /**
271
- * Returns the full ApiContext associated with this gateway instance.
272
- * The context carries request-scoped values: userId, spaceId, headers,
273
- * other gateways, cores, db, etc.
274
- */
275
- getContext(): ApiContext;
276
- /**
277
- * Returns all gateway instances from the current request context.
278
- * Allows one gateway to call another (e.g. UserGateway calling RoleGateway)
279
- * without going through a core, using the same shared context and db connection.
280
- *
281
- * Returns an empty object if context is not available.
282
- */
283
- getGateways(): Record<string, any>;
284
- /**
285
- * Returns the Database instance from config.
286
- * All query builders are derived from this instance.
287
- */
288
- getDb(): Database | undefined;
289
- /**
290
- * Returns a Knex query builder scoped to this gateway's table.
291
- * The builder is a fresh instance each time — it does not carry state
292
- * between calls.
293
- */
294
- getBuilder(): any;
295
- /**
296
- * Returns the primary key field name used for SELECT and loader operations.
297
- * Defaults to the global ID_FIELD constant if not set in config.
298
- *
299
- * Note: this may differ from `getIdFieldUpdateRemove()` — some tables use
300
- * a different column for update/delete filtering (e.g. a composite key)
301
- * while listing and loading still uses the primary key.
302
- */
303
- getIdField(): string;
304
- /**
305
- * Returns the field name used to identify records in UPDATE and DELETE
306
- * WHERE clauses. Falls back through idFieldUpdateRemove → idField → ID_FIELD.
307
- *
308
- * Separate from `getIdField()` to support tables where the logical primary
309
- * key used for loading differs from the column used for writes
310
- * (e.g. a table with a UUID primary key but a separate "slug" as update target).
311
- */
312
- getIdFieldUpdateRemove(): string;
313
508
  /**
314
509
  * Loads a single record by id via the loader (DataCache/DataLoader).
315
510
  * Leverages DataLoader batching — multiple `get()` calls within the same
@@ -490,5 +685,30 @@ declare class BaseGateway {
490
685
  * `transformOnOut()`.
491
686
  */
492
687
  remove(where: any): Promise<any[]>;
688
+ /**
689
+ * Returns the count of non-removed rows matching the given filter.
690
+ *
691
+ * Applies the same soft-delete, space, and user scoping that list() uses,
692
+ * ensuring count() and list() always agree on which rows are "visible" for
693
+ * an identical filter. Uses COUNT(*) — no column data is read, so this is
694
+ * as cheap as possible on both PostgreSQL and MS Azure SQL.
695
+ *
696
+ * Filter application order (mirrors list()):
697
+ * 1. Soft-delete guard — WHERE Removed_By IS NULL (when hasRemovedBy)
698
+ * WHERE Removed_At IS NULL (when hasRemovedAt and
699
+ * not hasRemovedBy — rare, but handled for safety)
700
+ * 2. Space scoping — WHERE Space_ID = context.spaceId (if hasSpace)
701
+ * 3. User scoping — WHERE {filterByUserField} = context.userId (if set)
702
+ * 4. onCountFilter() hook — subclass custom logic
703
+ * 5. Declarative rules — countFilters when set, otherwise listFilters
704
+ *
705
+ * Subclasses that need count with different scoping than list have two options:
706
+ * A) Set explicit countFilters in the constructor props.
707
+ * B) Override onCountFilter() for logic that declarative rules cannot express.
708
+ *
709
+ * @param filterParams Filter object (same shape as passed to list())
710
+ * @returns Row count as a number; 0 when nothing matches or on error
711
+ */
712
+ count(filterParams: any): Promise<number>;
493
713
  }
494
714
  export { BaseGateway };