@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.
- package/README.md +208 -45
- package/build/BaseGateway.d.ts +270 -50
- package/build/BaseGateway.js +551 -64
- package/build/Database.d.ts +15 -0
- package/build/Database.js +17 -1
- package/build/esm/BaseGateway.d.ts +270 -50
- package/build/esm/BaseGateway.js +552 -65
- package/build/esm/Database.d.ts +15 -0
- package/build/esm/Database.js +17 -1
- package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +71 -0
- package/build/esm/interfaces/BaseGatewayPropsInterface.js +0 -1
- package/build/esm/interfaces/GatewayFilterRule.d.ts +109 -0
- package/build/esm/interfaces/GatewayFilterRule.js +1 -0
- package/build/esm/interfaces/index.d.ts +1 -0
- package/build/esm/interfaces/index.js +1 -0
- package/build/interfaces/BaseGatewayPropsInterface.d.ts +71 -0
- package/build/interfaces/BaseGatewayPropsInterface.js +0 -1
- package/build/interfaces/GatewayFilterRule.d.ts +109 -0
- package/build/interfaces/GatewayFilterRule.js +2 -0
- package/build/interfaces/index.d.ts +1 -0
- package/build/interfaces/index.js +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -720,24 +720,174 @@ export { NoteGw };
|
|
|
720
720
|
|
|
721
721
|
#### Gateway config flags
|
|
722
722
|
|
|
723
|
-
| Flag
|
|
724
|
-
|
|
|
725
|
-
| `table`
|
|
726
|
-
| `idField`
|
|
727
|
-
| `
|
|
728
|
-
| `
|
|
729
|
-
| `
|
|
730
|
-
| `
|
|
731
|
-
| `
|
|
732
|
-
| `
|
|
733
|
-
| `
|
|
734
|
-
| `
|
|
735
|
-
| `
|
|
736
|
-
| `
|
|
737
|
-
| `
|
|
738
|
-
| `
|
|
739
|
-
| `
|
|
740
|
-
| `
|
|
723
|
+
| Flag | Type | Description |
|
|
724
|
+
| ---------------------- | --------------------- | ------------------------------------------------------------------------------------------------ |
|
|
725
|
+
| `table` | `string` | Database table name |
|
|
726
|
+
| `idField` | `string` | Primary key for SELECT/loader — table-qualify for joined queries (default: `id`) |
|
|
727
|
+
| `idFieldAs` | `string` | Alias for the id column when it differs from the lookup key |
|
|
728
|
+
| `idFieldUpdateRemove` | `string` | Primary key for UPDATE/DELETE WHERE — must be unqualified |
|
|
729
|
+
| `setFields` | `string \| string[]` | Conflict target field(s) for the `set()` upsert operation |
|
|
730
|
+
| `mergeFields` | `string[]` | Explicit field list for the ON CONFLICT MERGE clause |
|
|
731
|
+
| `hasStatus` | `boolean` | Status filtering and REMOVED guard |
|
|
732
|
+
| `hasCreatedAt` | `boolean` | Auto-set `created_at` on insert |
|
|
733
|
+
| `hasUpdatedAt` | `boolean` | Auto-set `updated_at` on update |
|
|
734
|
+
| `hasRemovedAt` | `boolean` | Soft-delete via `removed_at` timestamp |
|
|
735
|
+
| `hasRemovedAtStr` | `boolean` | Also writes a formatted string timestamp to `removed_at_str` |
|
|
736
|
+
| `hasCreatedBy` | `boolean` | Auto-set `created_by` from `context.userId` on insert |
|
|
737
|
+
| `hasUpdatedBy` | `boolean` | Auto-set `updated_by` from `context.userId` on update |
|
|
738
|
+
| `hasRemovedBy` | `boolean` | Auto-set `removed_by` from `context.userId` on soft-delete |
|
|
739
|
+
| `hasSpace` | `boolean` | Scopes reads/writes to `context.spaceId` |
|
|
740
|
+
| `hasUserId` | `boolean` | Sets `userId` from context on create |
|
|
741
|
+
| `hasVersion` | `boolean` | Optimistic locking via version field |
|
|
742
|
+
| `hasLang` | `boolean` | Language-scoped records |
|
|
743
|
+
| `localizationForField` | `string` | Field combined with `lang` to build a composite localisation id |
|
|
744
|
+
| `hardRemove` | `boolean` | Hard DELETE instead of soft-delete |
|
|
745
|
+
| `noCache` | `boolean` | Bypass DataLoader cache |
|
|
746
|
+
| `returnFields` | `string[]` | Columns in RETURNING clause (default: `['*']`) |
|
|
747
|
+
| `defaultSorting` | `SortItemInterface[]` | Default ORDER BY when none provided |
|
|
748
|
+
| `filterByUserField` | `string` | Auto-scope list queries to `context.userId` |
|
|
749
|
+
| `fieldForKeyword` | `string` | Column to apply keyword ILIKE/LIKE search against |
|
|
750
|
+
| `selectFields` | `string[]` | Columns selected when `useCache: false` (default: `['*']`) |
|
|
751
|
+
| `activeStatuses` | `number[]` | Status values considered active for list filtering |
|
|
752
|
+
| `insertChunkSize` | `number` | Records per INSERT batch — prevents DB parameter limit errors (default: `2500`) |
|
|
753
|
+
| `listFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `list()` — see [Declarative filter rules](#declarative-filter-rules) |
|
|
754
|
+
| `updateFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `update()` |
|
|
755
|
+
| `removeFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `remove()` |
|
|
756
|
+
| `countFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `count()` — falls back to `listFilters` when not set |
|
|
757
|
+
|
|
758
|
+
#### Filter hooks
|
|
759
|
+
|
|
760
|
+
| Hook | Signature | Purpose |
|
|
761
|
+
| ---------------- | ----------------------------------------------------- | -------------------------------------------------------------- |
|
|
762
|
+
| `onListFilter` | `(query, filterParams) => Promise<void>` | Custom WHERE clauses for `list()` |
|
|
763
|
+
| `onUpdateFilter` | `(query, whereParams) => Promise<number>` | Custom WHERE clauses for `update()` — return incremented count |
|
|
764
|
+
| `onRemoveFilter` | `(query, whereParams) => Promise<number>` | Custom WHERE clauses for `remove()` — return incremented count |
|
|
765
|
+
| `onCountFilter` | `(query, filterParams) => void` | Custom WHERE clauses for `count()` |
|
|
766
|
+
| `buildListQuery` | `(args: BuildListQueryArgsInterface) => Promise<any>` | Override to add JOINs and computed columns to list queries |
|
|
767
|
+
|
|
768
|
+
Always call `super.onListFilter()` / `super.onUpdateFilter()` / `super.onRemoveFilter()` at the top of any override so base-class scoping (soft-delete, space, user) runs first.
|
|
769
|
+
|
|
770
|
+
---
|
|
771
|
+
|
|
772
|
+
#### Declarative filter rules
|
|
773
|
+
|
|
774
|
+
For the common case of simple equality or array `IN` filters, declarative rules eliminate the need to override `onListFilter`, `onUpdateFilter`, `onRemoveFilter`, or `onCountFilter` at all. Rules are passed in the constructor props and applied automatically after the base-class scoping logic.
|
|
775
|
+
|
|
776
|
+
```typescript
|
|
777
|
+
class PartyGuestGw extends BaseGateway {
|
|
778
|
+
private static readonly DOMAIN_FILTER_RULES = [
|
|
779
|
+
{ field: 'partyId', column: 'Party_Guest.Party_ID', type: 'array' as const },
|
|
780
|
+
{ field: 'rsvpStatus', column: 'Party_Guest.Rsvp_Status', type: 'array' as const },
|
|
781
|
+
{ field: 'wasInvited', column: 'Party_Guest.Invited_At', type: 'nullableBool' as const },
|
|
782
|
+
{ field: 'rsvpAt', column: 'Party_Guest.Rsvp_At', type: 'nullableDateRange' as const },
|
|
783
|
+
{ field: 'isStarred', column: 'Party_Guest.Is_Starred', type: 'bool' as const },
|
|
784
|
+
{
|
|
785
|
+
field: 'search',
|
|
786
|
+
column: '',
|
|
787
|
+
type: 'search' as const,
|
|
788
|
+
columns: ['Person.First_Name', 'Person.Last_Name', 'Person.Email'],
|
|
789
|
+
},
|
|
790
|
+
];
|
|
791
|
+
|
|
792
|
+
constructor(props: BaseGatewayPropsInterface) {
|
|
793
|
+
super({
|
|
794
|
+
...props,
|
|
795
|
+
table: TABLES.PARTY_GUEST,
|
|
796
|
+
listFilters: PartyGuestGw.DOMAIN_FILTER_RULES,
|
|
797
|
+
updateFilters: PartyGuestGw.DOMAIN_FILTER_RULES,
|
|
798
|
+
removeFilters: PartyGuestGw.DOMAIN_FILTER_RULES,
|
|
799
|
+
// countFilters omitted — BaseGateway falls back to listFilters automatically
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
```
|
|
804
|
+
|
|
805
|
+
**Best practice:** define the rules once as a `private static readonly` constant and reference it from all four filter props. This ensures `list`, `update`, `remove`, and `count` always stay in sync without duplicating the field/column/type data.
|
|
806
|
+
|
|
807
|
+
#### Filter rule types
|
|
808
|
+
|
|
809
|
+
Each `GatewayFilterRule` has a `type` that determines the WHERE clause strategy:
|
|
810
|
+
|
|
811
|
+
| Type | Behaviour |
|
|
812
|
+
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
813
|
+
| `array` | `whereIn(column, values)` for arrays; `where(column, value)` for scalars. Skipped when value is `null`/`undefined`/`''`. |
|
|
814
|
+
| `eq` | `where(column, value)`. Strict single-value equality — never expands to `whereIn`. Skipped when value is `null`/`undefined`. |
|
|
815
|
+
| `bool` | `where(column, true\|false)`. Fires only on strict `true` or `false`; `null`/`undefined` leaves the column unconstrained. |
|
|
816
|
+
| `nullableBool` | `true` → `whereNotNull(column)` / `false` → `whereNull(column)` / `null`/`undefined` → skipped. Use when a nullable datetime encodes presence (e.g. `invitedAt IS [NOT] NULL`). |
|
|
817
|
+
| `dateRange` | Reads `filter[field + 'From']` and `filter[field + 'To']`. Applies `>=` and/or `<=` bounds independently. The `field` value is the base name (e.g. `'rsvpAt'`); actual keys are `rsvpAtFrom` / `rsvpAtTo`. |
|
|
818
|
+
| `nullableDateRange` | Extends `dateRange` with a `filter[field + 'Null']` boolean: `true` → `whereNull` (from/to skipped); `false` → `whereNotNull` (from/to still applied); `null`/`undefined` → null-ness unconstrained. |
|
|
819
|
+
| `search` | `LIKE`/`ILIKE` across one or more columns with OR semantics. Reads `filter[field]` (string). Requires the `columns` array on the rule. The operator is resolved per-database (`ilike` on PostgreSQL, `like` on MSSQL/MySQL). |
|
|
820
|
+
|
|
821
|
+
Rules with unsupported types on `updateFilters`/`removeFilters` (`search`, `dateRange`, `nullableDateRange`) are silently skipped with a warning — update and remove filters must be precise identifiers.
|
|
822
|
+
|
|
823
|
+
#### count()
|
|
824
|
+
|
|
825
|
+
Returns the count of non-removed rows matching a filter. Applies the same soft-delete, space, and user scoping as `list()`, then runs `onCountFilter()` and the declarative `countFilters` rules (falling back to `listFilters` when `countFilters` is not set).
|
|
826
|
+
|
|
827
|
+
```typescript
|
|
828
|
+
// In a core method:
|
|
829
|
+
const total = await this.gateway.count({ partyId: args.partyId, rsvpStatus: [1, 2] });
|
|
830
|
+
```
|
|
831
|
+
|
|
832
|
+
Gateways that already declare `listFilters` get `count()` for free with no additional configuration. Set `countFilters` explicitly only when count needs different scoping than list.
|
|
833
|
+
|
|
834
|
+
To add custom WHERE logic beyond what declarative rules express, override `onCountFilter()`:
|
|
835
|
+
|
|
836
|
+
```typescript
|
|
837
|
+
protected onCountFilter(query: any, filterParams: any): void {
|
|
838
|
+
if (filterParams?.accountId) {
|
|
839
|
+
query.where(`${TABLES.PARTY}.${FIELDS.ACCOUNT_ID}`, filterParams.accountId);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
```
|
|
843
|
+
|
|
844
|
+
---
|
|
845
|
+
|
|
846
|
+
#### Join-variant gateways
|
|
847
|
+
|
|
848
|
+
For read operations that need columns from related tables alongside the primary table, create additional read-only gateway variants that add JOINs via `buildListQuery`. The base gateway remains the sole source of truth for mutations.
|
|
849
|
+
|
|
850
|
+
```typescript
|
|
851
|
+
// PartyGuestGw — base gateway: all mutations, count(), plain reads
|
|
852
|
+
// PartyGuestWithMainPersonGw — read-only: joins Person for name/email/phone
|
|
853
|
+
// PartyGuestWithFullPersonGw — read-only: joins Person + avatar + extra fields
|
|
854
|
+
|
|
855
|
+
class PartyGuestWithMainPersonGw extends PartyGuestGw {
|
|
856
|
+
constructor(props: BaseGatewayPropsInterface) {
|
|
857
|
+
super({
|
|
858
|
+
...props,
|
|
859
|
+
// Each variant must have a unique keyPrefix to prevent DataLoader
|
|
860
|
+
// cache collisions between plain and joined result sets.
|
|
861
|
+
keyPrefix: 'party-guest-with-person',
|
|
862
|
+
selectFields: [
|
|
863
|
+
`${TABLES.PARTY_GUEST}.*`,
|
|
864
|
+
`${TABLES.PERSON}.${FIELDS.FIRST_NAME}`,
|
|
865
|
+
`${TABLES.PERSON}.${FIELDS.EMAIL}`,
|
|
866
|
+
`${TABLES.PERSON}.${FIELDS.PHONE}`,
|
|
867
|
+
],
|
|
868
|
+
});
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
// Join logic lives in buildListQuery, not in list() itself.
|
|
872
|
+
// This ensures the framework's cache/direct-query branching is respected —
|
|
873
|
+
// when useCache is true, only ids are selected here and the DataLoader
|
|
874
|
+
// hydrates records; the join only fires on the useCache: false path.
|
|
875
|
+
protected async buildListQuery(args: BuildListQueryArgsInterface): Promise<any> {
|
|
876
|
+
const query = await super.buildListQuery(args);
|
|
877
|
+
|
|
878
|
+
query.leftJoin(TABLES.PERSON, `${TABLES.PERSON}.${FIELDS.ID}`, `${TABLES.PARTY_GUEST}.${FIELDS.PERSON_ID}`);
|
|
879
|
+
|
|
880
|
+
return query;
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
```
|
|
884
|
+
|
|
885
|
+
**Rules for join-variant gateways:**
|
|
886
|
+
|
|
887
|
+
- **Mutations always go through the base gateway** — join variants are strictly read-only
|
|
888
|
+
- **Each variant needs a unique `keyPrefix`** — prevents cross-contamination between plain and joined result sets in the DataLoader cache
|
|
889
|
+
- **Join logic belongs in `buildListQuery`**, not in `onListFilter` or `list()` — this respects the framework's `useCache` branching
|
|
890
|
+
- **`idField` must be table-qualified** in the base gateway (`Party_Guest.ID`) to prevent ambiguity in joined queries
|
|
741
891
|
|
|
742
892
|
---
|
|
743
893
|
|
|
@@ -1593,13 +1743,22 @@ const isCorrect = await checkPassword(plaintextPassword, storedHash);
|
|
|
1593
1743
|
```typescript
|
|
1594
1744
|
import { FIELDS, HEADERS, ORDER_BYS, ID_TYPES } from '@sdflc/backend-helpers';
|
|
1595
1745
|
|
|
1746
|
+
// Primary key and standard columns
|
|
1596
1747
|
FIELDS.ID; // 'id'
|
|
1597
1748
|
FIELDS.STATUS; // 'status'
|
|
1598
|
-
FIELDS.CREATED_AT; // 'created_at'
|
|
1599
1749
|
FIELDS.SPACE_ID; // 'space_id'
|
|
1600
1750
|
FIELDS.USER_ID; // 'user_id'
|
|
1601
1751
|
FIELDS.LANG; // 'lang'
|
|
1602
1752
|
FIELDS.ORDER_NO; // 'order_no'
|
|
1753
|
+
FIELDS.VERSION; // 'version'
|
|
1754
|
+
|
|
1755
|
+
// Audit / timestamp columns
|
|
1756
|
+
FIELDS.CREATED_AT; // 'created_at'
|
|
1757
|
+
FIELDS.UPDATED_AT; // 'updated_at'
|
|
1758
|
+
FIELDS.REMOVED_AT; // 'removed_at'
|
|
1759
|
+
FIELDS.CREATED_BY; // 'created_by'
|
|
1760
|
+
FIELDS.UPDATED_BY; // 'updated_by'
|
|
1761
|
+
FIELDS.REMOVED_BY; // 'removed_by' ← soft-delete sentinel used by BaseGateway.count()
|
|
1603
1762
|
|
|
1604
1763
|
HEADERS.AUTHORIZATION; // 'authorization'
|
|
1605
1764
|
HEADERS.SPACE_ID; // 'x-space-id'
|
|
@@ -1620,29 +1779,33 @@ ORDER_BYS.DESC; // 'desc'
|
|
|
1620
1779
|
|
|
1621
1780
|
## Interfaces reference
|
|
1622
1781
|
|
|
1623
|
-
| Interface | Description
|
|
1624
|
-
| ----------------------------------------- |
|
|
1625
|
-
| `ApiContext` | Request context object shape
|
|
1626
|
-
| `ApiContextInterface` | Arguments for `createApiContext()`
|
|
1627
|
-
| `BaseCorePropsInterface` | Constructor props for `BaseCore` subclasses
|
|
1628
|
-
| `BaseCoreRateLimitOnActionInterface` | Per-action rate-limit rule map used in `BaseCorePropsInterface`
|
|
1629
|
-
| `BaseGatewayPropsInterface` | Constructor props for `BaseGateway` subclasses
|
|
1630
|
-
| `BaseExternalApiGatewayPropsInterface` | Constructor props for `BaseExternalApiGateway`
|
|
1631
|
-
| `BaseRestApiCrudControllerPropsInterface` | Constructor props for `BaseRestApiCrudController`
|
|
1632
|
-
| `BuildDefaultResolvers` | Arguments for `buildDefaultResolvers()`
|
|
1633
|
-
| `
|
|
1634
|
-
| `
|
|
1635
|
-
| `
|
|
1636
|
-
| `
|
|
1637
|
-
| `
|
|
1638
|
-
| `
|
|
1639
|
-
| `
|
|
1640
|
-
| `
|
|
1641
|
-
| `
|
|
1642
|
-
| `
|
|
1643
|
-
| `
|
|
1644
|
-
| `
|
|
1645
|
-
| `
|
|
1646
|
-
| `
|
|
1647
|
-
| `
|
|
1648
|
-
| `
|
|
1782
|
+
| Interface | Description |
|
|
1783
|
+
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1784
|
+
| `ApiContext` | Request context object shape |
|
|
1785
|
+
| `ApiContextInterface` | Arguments for `createApiContext()` |
|
|
1786
|
+
| `BaseCorePropsInterface` | Constructor props for `BaseCore` subclasses |
|
|
1787
|
+
| `BaseCoreRateLimitOnActionInterface` | Per-action rate-limit rule map used in `BaseCorePropsInterface` |
|
|
1788
|
+
| `BaseGatewayPropsInterface` | Constructor props for `BaseGateway` subclasses |
|
|
1789
|
+
| `BaseExternalApiGatewayPropsInterface` | Constructor props for `BaseExternalApiGateway` |
|
|
1790
|
+
| `BaseRestApiCrudControllerPropsInterface` | Constructor props for `BaseRestApiCrudController` |
|
|
1791
|
+
| `BuildDefaultResolvers` | Arguments for `buildDefaultResolvers()` |
|
|
1792
|
+
| `BuildListQueryArgsInterface` | Arguments passed to `buildListQuery()` overrides: `{ filter, params, fieldsToUse, useCache }` |
|
|
1793
|
+
| `BuildConfigOptions` | Options for `buildConfig()` |
|
|
1794
|
+
| `DatabaseOptions` | Options for `Database` constructor |
|
|
1795
|
+
| `DatabaseReadInterface` | Arguments for `Database.read()` |
|
|
1796
|
+
| `CacheInterface` | Config for `DataCache` (without request context) |
|
|
1797
|
+
| `DataCachePropsInterface` | Full props for `DataCache` including request context |
|
|
1798
|
+
| `LoaderInterface` | Interface for custom loaders (`load`, `loadMany`, `clear`, `prime`) |
|
|
1799
|
+
| `GatewayFilterRule` | Single declarative filter rule: `{ field, column, type, columns? }` — used by `listFilters` / `updateFilters` / `removeFilters` / `countFilters` |
|
|
1800
|
+
| `GatewayFilterType` | Union of filter strategy names: `'array' \| 'eq' \| 'bool' \| 'nullableBool' \| 'dateRange' \| 'nullableDateRange' \| 'search'` |
|
|
1801
|
+
| `SortItemInterface` | Single sort descriptor: `{ name: string, order: 'asc' \| 'desc' }` |
|
|
1802
|
+
| `RateLimitRule` | Rate-limit rule shape: `{ limit, windowSec, action? }` |
|
|
1803
|
+
| `RateLimiterInterface` | Structural interface for custom rate-limiter implementations |
|
|
1804
|
+
| `IpRateLimiter` | Built-in Redis-backed rate limiter; constructed automatically from `redisClient` |
|
|
1805
|
+
| `CoreActionInterface` | Arguments for `BaseCore.runAction()` including `tryAuth` and `rateLimit` |
|
|
1806
|
+
| `CreateUserTokenArgs` | Options for `createUserToken()` |
|
|
1807
|
+
| `VerifyUserTokenArgs` | Options for `verifyUserToken()` |
|
|
1808
|
+
| `UserTokenParams` | JWT payload structure |
|
|
1809
|
+
| `DownloadFileArgs` | Arguments for `downloadFile()` |
|
|
1810
|
+
| `DbFieldAddDefaultInterface` | Options for `dbFieldAddDefaults()` |
|
|
1811
|
+
| `ListArgsInterface` | Standard list operation arguments |
|