@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,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,6 +369,7 @@ 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>;
146
375
  /**
@@ -262,54 +491,6 @@ declare class BaseGateway {
262
491
  * must be handled in the loader's priming logic or in the calling code.
263
492
  */
264
493
  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
494
  /**
314
495
  * Loads a single record by id via the loader (DataCache/DataLoader).
315
496
  * Leverages DataLoader batching — multiple `get()` calls within the same