@sdflc/backend-helpers 1.0.123 → 1.0.125
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 +263 -45
- package/build/BaseCore.d.ts +40 -0
- package/build/BaseCore.js +58 -0
- package/build/BaseGateway.d.ts +39 -0
- package/build/BaseGateway.js +80 -0
- package/build/esm/BaseCore.d.ts +40 -0
- package/build/esm/BaseCore.js +58 -0
- package/build/esm/BaseGateway.d.ts +39 -0
- package/build/esm/BaseGateway.js +81 -1
- package/build/esm/interfaces/BaseCoreActionsInterface.d.ts +26 -0
- package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +17 -0
- package/build/interfaces/BaseCoreActionsInterface.d.ts +26 -0
- package/build/interfaces/BaseGatewayPropsInterface.d.ts +17 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -661,6 +661,61 @@ return this.runAction({
|
|
|
661
661
|
|
|
662
662
|
---
|
|
663
663
|
|
|
664
|
+
#### Action-scoped request store
|
|
665
|
+
|
|
666
|
+
When you need to share data between a `before*` hook and its corresponding `after*` hook — for example, fetching a record once before an update and reusing it for audit logging afterward — `BaseCore` provides a typed key-value store scoped to a single action invocation. A fresh store is created for every `runAction` call, so there is no bleed between `list()`, `create()`, etc., even on the same core instance.
|
|
667
|
+
|
|
668
|
+
Use the three protected helpers from any `before*`, `after*`, `validate`, or `action` handler:
|
|
669
|
+
|
|
670
|
+
| Method | Signature | Description |
|
|
671
|
+
| ------------------ | ---------------------------------- | ------------------------------------------------------------------------- |
|
|
672
|
+
| `storeSet<T>` | `(opt, key, value) → T` | Stores a value; returns it as a pass-through |
|
|
673
|
+
| `storeGet<T>` | `(opt, key) → T \| undefined` | Retrieves a typed value; `undefined` when absent |
|
|
674
|
+
| `storeGetOrSet<T>` | `(opt, key, factory) → Promise<T>` | Returns stored value or calls `factory()`, stores, and returns the result |
|
|
675
|
+
|
|
676
|
+
Define keys as constants to catch typos at compile time:
|
|
677
|
+
|
|
678
|
+
```typescript
|
|
679
|
+
// src/core/ProductCore.ts
|
|
680
|
+
const STORE = {
|
|
681
|
+
ORIGINAL_RECORD: 'originalRecord',
|
|
682
|
+
PARENT_CATEGORY: 'parentCategory',
|
|
683
|
+
} as const;
|
|
684
|
+
|
|
685
|
+
class ProductCore extends AppCore {
|
|
686
|
+
async beforeUpdate(params: any, opt: BaseCoreActionsInterface): Promise<any> {
|
|
687
|
+
// Fetch the current record once; storeGetOrSet avoids a second DB hit if
|
|
688
|
+
// another hook already loaded it.
|
|
689
|
+
const current = await this.storeGetOrSet(opt, STORE.ORIGINAL_RECORD, () =>
|
|
690
|
+
this.getGateway().get(opt.args?.where?.id),
|
|
691
|
+
);
|
|
692
|
+
|
|
693
|
+
this.logger.debug(`Updating product, original slug was '${current?.slug}'`);
|
|
694
|
+
return this.processItemOnIn(params, opt);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
async afterUpdate(items: any[], opt: BaseCoreActionsInterface): Promise<any> {
|
|
698
|
+
const original = this.storeGet<{ slug: string }>(opt, STORE.ORIGINAL_RECORD);
|
|
699
|
+
|
|
700
|
+
if (original?.slug && items[0]?.slug !== original.slug) {
|
|
701
|
+
this.logger.log(`Product slug changed from '${original.slug}' to '${items[0]?.slug}'; updating references`);
|
|
702
|
+
// trigger side effects — redirect rules, search index update, etc.
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
return Promise.all(items.map((item) => this.processItemOnOut(item, opt)));
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
```
|
|
709
|
+
|
|
710
|
+
**Notes:**
|
|
711
|
+
|
|
712
|
+
- Prefer `storeGetOrSet` for anything fetched from the database — it guarantees at most one DB call per action invocation regardless of how many hooks reference the same key.
|
|
713
|
+
- The store is also available inside the `validate` function and the inline `action` handler passed to `runAction()` via the `opt` argument.
|
|
714
|
+
- The store is not shared between a parent call and a nested same-request call — each `runAction` invocation gets its own independent `Map`.
|
|
715
|
+
- `storeGet` uses `Map.has()` internally, so storing `null` or `false` is treated as a hit, not a miss.
|
|
716
|
+
|
|
717
|
+
---
|
|
718
|
+
|
|
664
719
|
### BaseGateway
|
|
665
720
|
|
|
666
721
|
The base class for all database-backed data access. One gateway per table.
|
|
@@ -720,24 +775,174 @@ export { NoteGw };
|
|
|
720
775
|
|
|
721
776
|
#### Gateway config flags
|
|
722
777
|
|
|
723
|
-
| Flag
|
|
724
|
-
|
|
|
725
|
-
| `table`
|
|
726
|
-
| `idField`
|
|
727
|
-
| `
|
|
728
|
-
| `
|
|
729
|
-
| `
|
|
730
|
-
| `
|
|
731
|
-
| `
|
|
732
|
-
| `
|
|
733
|
-
| `
|
|
734
|
-
| `
|
|
735
|
-
| `
|
|
736
|
-
| `
|
|
737
|
-
| `
|
|
738
|
-
| `
|
|
739
|
-
| `
|
|
740
|
-
| `
|
|
778
|
+
| Flag | Type | Description |
|
|
779
|
+
| ---------------------- | --------------------- | ------------------------------------------------------------------------------------------------ |
|
|
780
|
+
| `table` | `string` | Database table name |
|
|
781
|
+
| `idField` | `string` | Primary key for SELECT/loader — table-qualify for joined queries (default: `id`) |
|
|
782
|
+
| `idFieldAs` | `string` | Alias for the id column when it differs from the lookup key |
|
|
783
|
+
| `idFieldUpdateRemove` | `string` | Primary key for UPDATE/DELETE WHERE — must be unqualified |
|
|
784
|
+
| `setFields` | `string \| string[]` | Conflict target field(s) for the `set()` upsert operation |
|
|
785
|
+
| `mergeFields` | `string[]` | Explicit field list for the ON CONFLICT MERGE clause |
|
|
786
|
+
| `hasStatus` | `boolean` | Status filtering and REMOVED guard |
|
|
787
|
+
| `hasCreatedAt` | `boolean` | Auto-set `created_at` on insert |
|
|
788
|
+
| `hasUpdatedAt` | `boolean` | Auto-set `updated_at` on update |
|
|
789
|
+
| `hasRemovedAt` | `boolean` | Soft-delete via `removed_at` timestamp |
|
|
790
|
+
| `hasRemovedAtStr` | `boolean` | Also writes a formatted string timestamp to `removed_at_str` |
|
|
791
|
+
| `hasCreatedBy` | `boolean` | Auto-set `created_by` from `context.userId` on insert |
|
|
792
|
+
| `hasUpdatedBy` | `boolean` | Auto-set `updated_by` from `context.userId` on update |
|
|
793
|
+
| `hasRemovedBy` | `boolean` | Auto-set `removed_by` from `context.userId` on soft-delete |
|
|
794
|
+
| `hasSpace` | `boolean` | Scopes reads/writes to `context.spaceId` |
|
|
795
|
+
| `hasUserId` | `boolean` | Sets `userId` from context on create |
|
|
796
|
+
| `hasVersion` | `boolean` | Optimistic locking via version field |
|
|
797
|
+
| `hasLang` | `boolean` | Language-scoped records |
|
|
798
|
+
| `localizationForField` | `string` | Field combined with `lang` to build a composite localisation id |
|
|
799
|
+
| `hardRemove` | `boolean` | Hard DELETE instead of soft-delete |
|
|
800
|
+
| `noCache` | `boolean` | Bypass DataLoader cache |
|
|
801
|
+
| `returnFields` | `string[]` | Columns in RETURNING clause (default: `['*']`) |
|
|
802
|
+
| `defaultSorting` | `SortItemInterface[]` | Default ORDER BY when none provided |
|
|
803
|
+
| `filterByUserField` | `string` | Auto-scope list queries to `context.userId` |
|
|
804
|
+
| `fieldForKeyword` | `string` | Column to apply keyword ILIKE/LIKE search against |
|
|
805
|
+
| `selectFields` | `string[]` | Columns selected when `useCache: false` (default: `['*']`) |
|
|
806
|
+
| `activeStatuses` | `number[]` | Status values considered active for list filtering |
|
|
807
|
+
| `insertChunkSize` | `number` | Records per INSERT batch — prevents DB parameter limit errors (default: `2500`) |
|
|
808
|
+
| `listFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `list()` — see [Declarative filter rules](#declarative-filter-rules) |
|
|
809
|
+
| `updateFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `update()` |
|
|
810
|
+
| `removeFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `remove()` |
|
|
811
|
+
| `countFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `count()` — falls back to `listFilters` when not set |
|
|
812
|
+
|
|
813
|
+
#### Filter hooks
|
|
814
|
+
|
|
815
|
+
| Hook | Signature | Purpose |
|
|
816
|
+
| ---------------- | ----------------------------------------------------- | -------------------------------------------------------------- |
|
|
817
|
+
| `onListFilter` | `(query, filterParams) => Promise<void>` | Custom WHERE clauses for `list()` |
|
|
818
|
+
| `onUpdateFilter` | `(query, whereParams) => Promise<number>` | Custom WHERE clauses for `update()` — return incremented count |
|
|
819
|
+
| `onRemoveFilter` | `(query, whereParams) => Promise<number>` | Custom WHERE clauses for `remove()` — return incremented count |
|
|
820
|
+
| `onCountFilter` | `(query, filterParams) => void` | Custom WHERE clauses for `count()` |
|
|
821
|
+
| `buildListQuery` | `(args: BuildListQueryArgsInterface) => Promise<any>` | Override to add JOINs and computed columns to list queries |
|
|
822
|
+
|
|
823
|
+
Always call `super.onListFilter()` / `super.onUpdateFilter()` / `super.onRemoveFilter()` at the top of any override so base-class scoping (soft-delete, space, user) runs first.
|
|
824
|
+
|
|
825
|
+
---
|
|
826
|
+
|
|
827
|
+
#### Declarative filter rules
|
|
828
|
+
|
|
829
|
+
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.
|
|
830
|
+
|
|
831
|
+
```typescript
|
|
832
|
+
class PartyGuestGw extends BaseGateway {
|
|
833
|
+
private static readonly DOMAIN_FILTER_RULES = [
|
|
834
|
+
{ field: 'partyId', column: 'Party_Guest.Party_ID', type: 'array' as const },
|
|
835
|
+
{ field: 'rsvpStatus', column: 'Party_Guest.Rsvp_Status', type: 'array' as const },
|
|
836
|
+
{ field: 'wasInvited', column: 'Party_Guest.Invited_At', type: 'nullableBool' as const },
|
|
837
|
+
{ field: 'rsvpAt', column: 'Party_Guest.Rsvp_At', type: 'nullableDateRange' as const },
|
|
838
|
+
{ field: 'isStarred', column: 'Party_Guest.Is_Starred', type: 'bool' as const },
|
|
839
|
+
{
|
|
840
|
+
field: 'search',
|
|
841
|
+
column: '',
|
|
842
|
+
type: 'search' as const,
|
|
843
|
+
columns: ['Person.First_Name', 'Person.Last_Name', 'Person.Email'],
|
|
844
|
+
},
|
|
845
|
+
];
|
|
846
|
+
|
|
847
|
+
constructor(props: BaseGatewayPropsInterface) {
|
|
848
|
+
super({
|
|
849
|
+
...props,
|
|
850
|
+
table: TABLES.PARTY_GUEST,
|
|
851
|
+
listFilters: PartyGuestGw.DOMAIN_FILTER_RULES,
|
|
852
|
+
updateFilters: PartyGuestGw.DOMAIN_FILTER_RULES,
|
|
853
|
+
removeFilters: PartyGuestGw.DOMAIN_FILTER_RULES,
|
|
854
|
+
// countFilters omitted — BaseGateway falls back to listFilters automatically
|
|
855
|
+
});
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
```
|
|
859
|
+
|
|
860
|
+
**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.
|
|
861
|
+
|
|
862
|
+
#### Filter rule types
|
|
863
|
+
|
|
864
|
+
Each `GatewayFilterRule` has a `type` that determines the WHERE clause strategy:
|
|
865
|
+
|
|
866
|
+
| Type | Behaviour |
|
|
867
|
+
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
868
|
+
| `array` | `whereIn(column, values)` for arrays; `where(column, value)` for scalars. Skipped when value is `null`/`undefined`/`''`. |
|
|
869
|
+
| `eq` | `where(column, value)`. Strict single-value equality — never expands to `whereIn`. Skipped when value is `null`/`undefined`. |
|
|
870
|
+
| `bool` | `where(column, true\|false)`. Fires only on strict `true` or `false`; `null`/`undefined` leaves the column unconstrained. |
|
|
871
|
+
| `nullableBool` | `true` → `whereNotNull(column)` / `false` → `whereNull(column)` / `null`/`undefined` → skipped. Use when a nullable datetime encodes presence (e.g. `invitedAt IS [NOT] NULL`). |
|
|
872
|
+
| `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`. |
|
|
873
|
+
| `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. |
|
|
874
|
+
| `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). |
|
|
875
|
+
|
|
876
|
+
Rules with unsupported types on `updateFilters`/`removeFilters` (`search`, `dateRange`, `nullableDateRange`) are silently skipped with a warning — update and remove filters must be precise identifiers.
|
|
877
|
+
|
|
878
|
+
#### count()
|
|
879
|
+
|
|
880
|
+
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).
|
|
881
|
+
|
|
882
|
+
```typescript
|
|
883
|
+
// In a core method:
|
|
884
|
+
const total = await this.gateway.count({ partyId: args.partyId, rsvpStatus: [1, 2] });
|
|
885
|
+
```
|
|
886
|
+
|
|
887
|
+
Gateways that already declare `listFilters` get `count()` for free with no additional configuration. Set `countFilters` explicitly only when count needs different scoping than list.
|
|
888
|
+
|
|
889
|
+
To add custom WHERE logic beyond what declarative rules express, override `onCountFilter()`:
|
|
890
|
+
|
|
891
|
+
```typescript
|
|
892
|
+
protected onCountFilter(query: any, filterParams: any): void {
|
|
893
|
+
if (filterParams?.accountId) {
|
|
894
|
+
query.where(`${TABLES.PARTY}.${FIELDS.ACCOUNT_ID}`, filterParams.accountId);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
```
|
|
898
|
+
|
|
899
|
+
---
|
|
900
|
+
|
|
901
|
+
#### Join-variant gateways
|
|
902
|
+
|
|
903
|
+
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.
|
|
904
|
+
|
|
905
|
+
```typescript
|
|
906
|
+
// PartyGuestGw — base gateway: all mutations, count(), plain reads
|
|
907
|
+
// PartyGuestWithMainPersonGw — read-only: joins Person for name/email/phone
|
|
908
|
+
// PartyGuestWithFullPersonGw — read-only: joins Person + avatar + extra fields
|
|
909
|
+
|
|
910
|
+
class PartyGuestWithMainPersonGw extends PartyGuestGw {
|
|
911
|
+
constructor(props: BaseGatewayPropsInterface) {
|
|
912
|
+
super({
|
|
913
|
+
...props,
|
|
914
|
+
// Each variant must have a unique keyPrefix to prevent DataLoader
|
|
915
|
+
// cache collisions between plain and joined result sets.
|
|
916
|
+
keyPrefix: 'party-guest-with-person',
|
|
917
|
+
selectFields: [
|
|
918
|
+
`${TABLES.PARTY_GUEST}.*`,
|
|
919
|
+
`${TABLES.PERSON}.${FIELDS.FIRST_NAME}`,
|
|
920
|
+
`${TABLES.PERSON}.${FIELDS.EMAIL}`,
|
|
921
|
+
`${TABLES.PERSON}.${FIELDS.PHONE}`,
|
|
922
|
+
],
|
|
923
|
+
});
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
// Join logic lives in buildListQuery, not in list() itself.
|
|
927
|
+
// This ensures the framework's cache/direct-query branching is respected —
|
|
928
|
+
// when useCache is true, only ids are selected here and the DataLoader
|
|
929
|
+
// hydrates records; the join only fires on the useCache: false path.
|
|
930
|
+
protected async buildListQuery(args: BuildListQueryArgsInterface): Promise<any> {
|
|
931
|
+
const query = await super.buildListQuery(args);
|
|
932
|
+
|
|
933
|
+
query.leftJoin(TABLES.PERSON, `${TABLES.PERSON}.${FIELDS.ID}`, `${TABLES.PARTY_GUEST}.${FIELDS.PERSON_ID}`);
|
|
934
|
+
|
|
935
|
+
return query;
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
```
|
|
939
|
+
|
|
940
|
+
**Rules for join-variant gateways:**
|
|
941
|
+
|
|
942
|
+
- **Mutations always go through the base gateway** — join variants are strictly read-only
|
|
943
|
+
- **Each variant needs a unique `keyPrefix`** — prevents cross-contamination between plain and joined result sets in the DataLoader cache
|
|
944
|
+
- **Join logic belongs in `buildListQuery`**, not in `onListFilter` or `list()` — this respects the framework's `useCache` branching
|
|
945
|
+
- **`idField` must be table-qualified** in the base gateway (`Party_Guest.ID`) to prevent ambiguity in joined queries
|
|
741
946
|
|
|
742
947
|
---
|
|
743
948
|
|
|
@@ -1593,13 +1798,22 @@ const isCorrect = await checkPassword(plaintextPassword, storedHash);
|
|
|
1593
1798
|
```typescript
|
|
1594
1799
|
import { FIELDS, HEADERS, ORDER_BYS, ID_TYPES } from '@sdflc/backend-helpers';
|
|
1595
1800
|
|
|
1801
|
+
// Primary key and standard columns
|
|
1596
1802
|
FIELDS.ID; // 'id'
|
|
1597
1803
|
FIELDS.STATUS; // 'status'
|
|
1598
|
-
FIELDS.CREATED_AT; // 'created_at'
|
|
1599
1804
|
FIELDS.SPACE_ID; // 'space_id'
|
|
1600
1805
|
FIELDS.USER_ID; // 'user_id'
|
|
1601
1806
|
FIELDS.LANG; // 'lang'
|
|
1602
1807
|
FIELDS.ORDER_NO; // 'order_no'
|
|
1808
|
+
FIELDS.VERSION; // 'version'
|
|
1809
|
+
|
|
1810
|
+
// Audit / timestamp columns
|
|
1811
|
+
FIELDS.CREATED_AT; // 'created_at'
|
|
1812
|
+
FIELDS.UPDATED_AT; // 'updated_at'
|
|
1813
|
+
FIELDS.REMOVED_AT; // 'removed_at'
|
|
1814
|
+
FIELDS.CREATED_BY; // 'created_by'
|
|
1815
|
+
FIELDS.UPDATED_BY; // 'updated_by'
|
|
1816
|
+
FIELDS.REMOVED_BY; // 'removed_by' ← soft-delete sentinel used by BaseGateway.count()
|
|
1603
1817
|
|
|
1604
1818
|
HEADERS.AUTHORIZATION; // 'authorization'
|
|
1605
1819
|
HEADERS.SPACE_ID; // 'x-space-id'
|
|
@@ -1620,29 +1834,33 @@ ORDER_BYS.DESC; // 'desc'
|
|
|
1620
1834
|
|
|
1621
1835
|
## Interfaces reference
|
|
1622
1836
|
|
|
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
|
-
| `
|
|
1837
|
+
| Interface | Description |
|
|
1838
|
+
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1839
|
+
| `ApiContext` | Request context object shape |
|
|
1840
|
+
| `ApiContextInterface` | Arguments for `createApiContext()` |
|
|
1841
|
+
| `BaseCorePropsInterface` | Constructor props for `BaseCore` subclasses |
|
|
1842
|
+
| `BaseCoreRateLimitOnActionInterface` | Per-action rate-limit rule map used in `BaseCorePropsInterface` |
|
|
1843
|
+
| `BaseGatewayPropsInterface` | Constructor props for `BaseGateway` subclasses |
|
|
1844
|
+
| `BaseExternalApiGatewayPropsInterface` | Constructor props for `BaseExternalApiGateway` |
|
|
1845
|
+
| `BaseRestApiCrudControllerPropsInterface` | Constructor props for `BaseRestApiCrudController` |
|
|
1846
|
+
| `BuildDefaultResolvers` | Arguments for `buildDefaultResolvers()` |
|
|
1847
|
+
| `BuildListQueryArgsInterface` | Arguments passed to `buildListQuery()` overrides: `{ filter, params, fieldsToUse, useCache }` |
|
|
1848
|
+
| `BuildConfigOptions` | Options for `buildConfig()` |
|
|
1849
|
+
| `DatabaseOptions` | Options for `Database` constructor |
|
|
1850
|
+
| `DatabaseReadInterface` | Arguments for `Database.read()` |
|
|
1851
|
+
| `CacheInterface` | Config for `DataCache` (without request context) |
|
|
1852
|
+
| `DataCachePropsInterface` | Full props for `DataCache` including request context |
|
|
1853
|
+
| `LoaderInterface` | Interface for custom loaders (`load`, `loadMany`, `clear`, `prime`) |
|
|
1854
|
+
| `GatewayFilterRule` | Single declarative filter rule: `{ field, column, type, columns? }` — used by `listFilters` / `updateFilters` / `removeFilters` / `countFilters` |
|
|
1855
|
+
| `GatewayFilterType` | Union of filter strategy names: `'array' \| 'eq' \| 'bool' \| 'nullableBool' \| 'dateRange' \| 'nullableDateRange' \| 'search'` |
|
|
1856
|
+
| `SortItemInterface` | Single sort descriptor: `{ name: string, order: 'asc' \| 'desc' }` |
|
|
1857
|
+
| `RateLimitRule` | Rate-limit rule shape: `{ limit, windowSec, action? }` |
|
|
1858
|
+
| `RateLimiterInterface` | Structural interface for custom rate-limiter implementations |
|
|
1859
|
+
| `IpRateLimiter` | Built-in Redis-backed rate limiter; constructed automatically from `redisClient` |
|
|
1860
|
+
| `CoreActionInterface` | Arguments for `BaseCore.runAction()` including `tryAuth` and `rateLimit` |
|
|
1861
|
+
| `CreateUserTokenArgs` | Options for `createUserToken()` |
|
|
1862
|
+
| `VerifyUserTokenArgs` | Options for `verifyUserToken()` |
|
|
1863
|
+
| `UserTokenParams` | JWT payload structure |
|
|
1864
|
+
| `DownloadFileArgs` | Arguments for `downloadFile()` |
|
|
1865
|
+
| `DbFieldAddDefaultInterface` | Options for `dbFieldAddDefaults()` |
|
|
1866
|
+
| `ListArgsInterface` | Standard list operation arguments |
|
package/build/BaseCore.d.ts
CHANGED
|
@@ -659,5 +659,45 @@ declare class BaseCore {
|
|
|
659
659
|
* @param args.gateway Gateway instance to query for the current max orderNo
|
|
660
660
|
*/
|
|
661
661
|
setOrderNo(args: any): Promise<void>;
|
|
662
|
+
/**
|
|
663
|
+
* Stores a typed value in the action-scoped request store.
|
|
664
|
+
*
|
|
665
|
+
* Prefer this over opt.requestStore.set() directly — the return value
|
|
666
|
+
* lets callers write `const v = this.storeSet(opt, key, expensiveValue)`
|
|
667
|
+
* without a separate declaration.
|
|
668
|
+
*
|
|
669
|
+
* @param opt The BaseCoreActionsInterface opt object from any hook
|
|
670
|
+
* @param key Unique string key — define keys as constants to avoid typos
|
|
671
|
+
* @param value Any value to store; retrieved with storeGet<T>()
|
|
672
|
+
* @returns The stored value (pass-through for convenience)
|
|
673
|
+
*/
|
|
674
|
+
protected storeSet<T>(opt: BaseCoreActionsInterface, key: string, value: T): T;
|
|
675
|
+
/**
|
|
676
|
+
* Retrieves a typed value from the action-scoped request store.
|
|
677
|
+
*
|
|
678
|
+
* Returns undefined when the key is absent. Use opt.requestStore.has(key)
|
|
679
|
+
* beforehand if you need to distinguish a stored undefined from a missing key.
|
|
680
|
+
*
|
|
681
|
+
* @param opt The BaseCoreActionsInterface opt object from any hook
|
|
682
|
+
* @param key The key used in a prior storeSet() call
|
|
683
|
+
*/
|
|
684
|
+
protected storeGet<T>(opt: BaseCoreActionsInterface, key: string): T | undefined;
|
|
685
|
+
/**
|
|
686
|
+
* Returns the stored value when present; otherwise calls factory(), stores
|
|
687
|
+
* the result, and returns it.
|
|
688
|
+
*
|
|
689
|
+
* Use for values that are expensive to compute (e.g. a DB fetch) and may
|
|
690
|
+
* be needed by multiple hooks in the same action invocation.
|
|
691
|
+
*
|
|
692
|
+
* Example — fetch a parent record once, reuse in both beforeUpdate and afterUpdate:
|
|
693
|
+
* const parent = await this.storeGetOrSet(opt, 'parentRecord', () =>
|
|
694
|
+
* this.getGateway('parentGw').get(params.parentId)
|
|
695
|
+
* );
|
|
696
|
+
*
|
|
697
|
+
* @param opt The BaseCoreActionsInterface opt object from any hook
|
|
698
|
+
* @param key Cache key — same string used by storeSet() / storeGet()
|
|
699
|
+
* @param factory Called on cache miss; may be async or sync
|
|
700
|
+
*/
|
|
701
|
+
protected storeGetOrSet<T>(opt: BaseCoreActionsInterface, key: string, factory: () => T | Promise<T>): Promise<T>;
|
|
662
702
|
}
|
|
663
703
|
export { BaseCore };
|
package/build/BaseCore.js
CHANGED
|
@@ -594,6 +594,7 @@ class BaseCore {
|
|
|
594
594
|
setStep,
|
|
595
595
|
sameRequest,
|
|
596
596
|
hasTransaction,
|
|
597
|
+
requestStore: new Map(),
|
|
597
598
|
};
|
|
598
599
|
try {
|
|
599
600
|
// ── Step 1: Rate limiting ──────────────────────────────────────────────
|
|
@@ -1486,5 +1487,62 @@ class BaseCore {
|
|
|
1486
1487
|
}
|
|
1487
1488
|
}
|
|
1488
1489
|
}
|
|
1490
|
+
// ─── Action-scoped request store helpers ──────────────────────────────────
|
|
1491
|
+
// These helpers provide typed access to the per-action requestStore carried
|
|
1492
|
+
// in BaseCoreActionsInterface.opt. Use them in any before*, after*, validate,
|
|
1493
|
+
// or action handler to share data across hooks within a single action
|
|
1494
|
+
// invocation without adding instance properties to the subclass.
|
|
1495
|
+
/**
|
|
1496
|
+
* Stores a typed value in the action-scoped request store.
|
|
1497
|
+
*
|
|
1498
|
+
* Prefer this over opt.requestStore.set() directly — the return value
|
|
1499
|
+
* lets callers write `const v = this.storeSet(opt, key, expensiveValue)`
|
|
1500
|
+
* without a separate declaration.
|
|
1501
|
+
*
|
|
1502
|
+
* @param opt The BaseCoreActionsInterface opt object from any hook
|
|
1503
|
+
* @param key Unique string key — define keys as constants to avoid typos
|
|
1504
|
+
* @param value Any value to store; retrieved with storeGet<T>()
|
|
1505
|
+
* @returns The stored value (pass-through for convenience)
|
|
1506
|
+
*/
|
|
1507
|
+
storeSet(opt, key, value) {
|
|
1508
|
+
opt.requestStore.set(key, value);
|
|
1509
|
+
return value;
|
|
1510
|
+
}
|
|
1511
|
+
/**
|
|
1512
|
+
* Retrieves a typed value from the action-scoped request store.
|
|
1513
|
+
*
|
|
1514
|
+
* Returns undefined when the key is absent. Use opt.requestStore.has(key)
|
|
1515
|
+
* beforehand if you need to distinguish a stored undefined from a missing key.
|
|
1516
|
+
*
|
|
1517
|
+
* @param opt The BaseCoreActionsInterface opt object from any hook
|
|
1518
|
+
* @param key The key used in a prior storeSet() call
|
|
1519
|
+
*/
|
|
1520
|
+
storeGet(opt, key) {
|
|
1521
|
+
return opt.requestStore.get(key);
|
|
1522
|
+
}
|
|
1523
|
+
/**
|
|
1524
|
+
* Returns the stored value when present; otherwise calls factory(), stores
|
|
1525
|
+
* the result, and returns it.
|
|
1526
|
+
*
|
|
1527
|
+
* Use for values that are expensive to compute (e.g. a DB fetch) and may
|
|
1528
|
+
* be needed by multiple hooks in the same action invocation.
|
|
1529
|
+
*
|
|
1530
|
+
* Example — fetch a parent record once, reuse in both beforeUpdate and afterUpdate:
|
|
1531
|
+
* const parent = await this.storeGetOrSet(opt, 'parentRecord', () =>
|
|
1532
|
+
* this.getGateway('parentGw').get(params.parentId)
|
|
1533
|
+
* );
|
|
1534
|
+
*
|
|
1535
|
+
* @param opt The BaseCoreActionsInterface opt object from any hook
|
|
1536
|
+
* @param key Cache key — same string used by storeSet() / storeGet()
|
|
1537
|
+
* @param factory Called on cache miss; may be async or sync
|
|
1538
|
+
*/
|
|
1539
|
+
async storeGetOrSet(opt, key, factory) {
|
|
1540
|
+
if (opt.requestStore.has(key)) {
|
|
1541
|
+
return opt.requestStore.get(key);
|
|
1542
|
+
}
|
|
1543
|
+
const value = await factory();
|
|
1544
|
+
opt.requestStore.set(key, value);
|
|
1545
|
+
return value;
|
|
1546
|
+
}
|
|
1489
1547
|
}
|
|
1490
1548
|
exports.BaseCore = BaseCore;
|
package/build/BaseGateway.d.ts
CHANGED
|
@@ -372,6 +372,20 @@ declare class BaseGateway {
|
|
|
372
372
|
* - `removeFilters` — applies declarative GatewayFilterRule array (new)
|
|
373
373
|
*/
|
|
374
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;
|
|
375
389
|
/**
|
|
376
390
|
* Transforms a params object before it is inserted into the database.
|
|
377
391
|
* Called once per object inside the `create()` loop, after the ID is generated.
|
|
@@ -671,5 +685,30 @@ declare class BaseGateway {
|
|
|
671
685
|
* `transformOnOut()`.
|
|
672
686
|
*/
|
|
673
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>;
|
|
674
713
|
}
|
|
675
714
|
export { BaseGateway };
|
package/build/BaseGateway.js
CHANGED
|
@@ -717,6 +717,22 @@ class BaseGateway {
|
|
|
717
717
|
filtersAppliedQty += this.applyDeclarativeRemoveFilters(query, filterParams);
|
|
718
718
|
return filtersAppliedQty;
|
|
719
719
|
}
|
|
720
|
+
/**
|
|
721
|
+
* Hook called by count() to apply custom WHERE conditions to the count query.
|
|
722
|
+
*
|
|
723
|
+
* Parallel to onListFilter() — override in subclasses that need filter logic
|
|
724
|
+
* beyond what the declarative countFilters rules can express (OR conditions,
|
|
725
|
+
* subqueries, cross-table joins, etc.).
|
|
726
|
+
*
|
|
727
|
+
* The base implementation is a no-op. Call super.onCountFilter() when
|
|
728
|
+
* overriding so future base-class logic is not silently skipped.
|
|
729
|
+
*
|
|
730
|
+
* @param query Knex query builder for the count query
|
|
731
|
+
* @param filterParams The raw filter object passed to count()
|
|
732
|
+
*/
|
|
733
|
+
onCountFilter(query, filterParams) {
|
|
734
|
+
// no-op — override in subclasses for custom count filter logic
|
|
735
|
+
}
|
|
720
736
|
// ─── Record transforms ─────────────────────────────────────────────────────
|
|
721
737
|
/**
|
|
722
738
|
* Transforms a params object before it is inserted into the database.
|
|
@@ -1310,6 +1326,70 @@ class BaseGateway {
|
|
|
1310
1326
|
}
|
|
1311
1327
|
return items.map((item) => this.transformOnOut(item));
|
|
1312
1328
|
}
|
|
1329
|
+
/**
|
|
1330
|
+
* Returns the count of non-removed rows matching the given filter.
|
|
1331
|
+
*
|
|
1332
|
+
* Applies the same soft-delete, space, and user scoping that list() uses,
|
|
1333
|
+
* ensuring count() and list() always agree on which rows are "visible" for
|
|
1334
|
+
* an identical filter. Uses COUNT(*) — no column data is read, so this is
|
|
1335
|
+
* as cheap as possible on both PostgreSQL and MS Azure SQL.
|
|
1336
|
+
*
|
|
1337
|
+
* Filter application order (mirrors list()):
|
|
1338
|
+
* 1. Soft-delete guard — WHERE Removed_By IS NULL (when hasRemovedBy)
|
|
1339
|
+
* WHERE Removed_At IS NULL (when hasRemovedAt and
|
|
1340
|
+
* not hasRemovedBy — rare, but handled for safety)
|
|
1341
|
+
* 2. Space scoping — WHERE Space_ID = context.spaceId (if hasSpace)
|
|
1342
|
+
* 3. User scoping — WHERE {filterByUserField} = context.userId (if set)
|
|
1343
|
+
* 4. onCountFilter() hook — subclass custom logic
|
|
1344
|
+
* 5. Declarative rules — countFilters when set, otherwise listFilters
|
|
1345
|
+
*
|
|
1346
|
+
* Subclasses that need count with different scoping than list have two options:
|
|
1347
|
+
* A) Set explicit countFilters in the constructor props.
|
|
1348
|
+
* B) Override onCountFilter() for logic that declarative rules cannot express.
|
|
1349
|
+
*
|
|
1350
|
+
* @param filterParams Filter object (same shape as passed to list())
|
|
1351
|
+
* @returns Row count as a number; 0 when nothing matches or on error
|
|
1352
|
+
*/
|
|
1353
|
+
async count(filterParams) {
|
|
1354
|
+
const query = this.getBuilder().count({ qty: '*' });
|
|
1355
|
+
// ── 1. Soft-delete guard ────────────────────────────────────────────────
|
|
1356
|
+
// In this codebase hasRemovedBy and hasRemovedAt are always set together
|
|
1357
|
+
// on the remove path — Removed_By is the primary sentinel. Guard on
|
|
1358
|
+
// Removed_By IS NULL first; fall back to Removed_At IS NULL for tables
|
|
1359
|
+
// that have a timestamp column but no author column (uncommon but valid).
|
|
1360
|
+
if (this.config.hasRemovedBy) {
|
|
1361
|
+
query.whereNull(`${this.config.table}.${constants_1.FIELDS.REMOVED_BY}`);
|
|
1362
|
+
}
|
|
1363
|
+
else if (this.config.hasRemovedAt) {
|
|
1364
|
+
query.whereNull(`${this.config.table}.${constants_1.FIELDS.REMOVED_AT}`);
|
|
1365
|
+
}
|
|
1366
|
+
// ── 2. Space scoping ────────────────────────────────────────────────────
|
|
1367
|
+
if (this.config.hasSpace && this.config.context?.spaceId) {
|
|
1368
|
+
query.where(`${this.config.table}.${constants_1.FIELDS.SPACE_ID}`, this.config.context.spaceId);
|
|
1369
|
+
}
|
|
1370
|
+
// ── 3. User scoping ─────────────────────────────────────────────────────
|
|
1371
|
+
if (this.config.filterByUserField && this.config.context?.userId) {
|
|
1372
|
+
query.where(`${this.config.table}.${this.config.filterByUserField}`, this.config.context.userId);
|
|
1373
|
+
}
|
|
1374
|
+
// ── 4. Subclass hook ────────────────────────────────────────────────────
|
|
1375
|
+
this.onCountFilter(query, filterParams);
|
|
1376
|
+
// ── 5. Declarative filter rules ─────────────────────────────────────────
|
|
1377
|
+
// Fall back to listFilters when countFilters is not explicitly configured.
|
|
1378
|
+
// This means gateways that already declare listFilters get count() for free
|
|
1379
|
+
// with no changes required.
|
|
1380
|
+
const rulesToApply = this.config.countFilters ?? this.config.listFilters ?? [];
|
|
1381
|
+
for (const rule of rulesToApply) {
|
|
1382
|
+
this.applyFilterRule(query, rule, filterParams);
|
|
1383
|
+
}
|
|
1384
|
+
this.logger.debug(`Executing count on table "${this.config.table}"`);
|
|
1385
|
+
const result = (0, utils_1.camelResponse)(await query);
|
|
1386
|
+
const qty = result?.[0]?.qty;
|
|
1387
|
+
if (qty == null) {
|
|
1388
|
+
this.logger.log(`Count query on "${this.config.table}" returned no result row — defaulting to 0`);
|
|
1389
|
+
return 0;
|
|
1390
|
+
}
|
|
1391
|
+
return Number(qty);
|
|
1392
|
+
}
|
|
1313
1393
|
}
|
|
1314
1394
|
exports.BaseGateway = BaseGateway;
|
|
1315
1395
|
// ─── Module-level helpers ──────────────────────────────────────────────────────
|
package/build/esm/BaseCore.d.ts
CHANGED
|
@@ -659,5 +659,45 @@ declare class BaseCore {
|
|
|
659
659
|
* @param args.gateway Gateway instance to query for the current max orderNo
|
|
660
660
|
*/
|
|
661
661
|
setOrderNo(args: any): Promise<void>;
|
|
662
|
+
/**
|
|
663
|
+
* Stores a typed value in the action-scoped request store.
|
|
664
|
+
*
|
|
665
|
+
* Prefer this over opt.requestStore.set() directly — the return value
|
|
666
|
+
* lets callers write `const v = this.storeSet(opt, key, expensiveValue)`
|
|
667
|
+
* without a separate declaration.
|
|
668
|
+
*
|
|
669
|
+
* @param opt The BaseCoreActionsInterface opt object from any hook
|
|
670
|
+
* @param key Unique string key — define keys as constants to avoid typos
|
|
671
|
+
* @param value Any value to store; retrieved with storeGet<T>()
|
|
672
|
+
* @returns The stored value (pass-through for convenience)
|
|
673
|
+
*/
|
|
674
|
+
protected storeSet<T>(opt: BaseCoreActionsInterface, key: string, value: T): T;
|
|
675
|
+
/**
|
|
676
|
+
* Retrieves a typed value from the action-scoped request store.
|
|
677
|
+
*
|
|
678
|
+
* Returns undefined when the key is absent. Use opt.requestStore.has(key)
|
|
679
|
+
* beforehand if you need to distinguish a stored undefined from a missing key.
|
|
680
|
+
*
|
|
681
|
+
* @param opt The BaseCoreActionsInterface opt object from any hook
|
|
682
|
+
* @param key The key used in a prior storeSet() call
|
|
683
|
+
*/
|
|
684
|
+
protected storeGet<T>(opt: BaseCoreActionsInterface, key: string): T | undefined;
|
|
685
|
+
/**
|
|
686
|
+
* Returns the stored value when present; otherwise calls factory(), stores
|
|
687
|
+
* the result, and returns it.
|
|
688
|
+
*
|
|
689
|
+
* Use for values that are expensive to compute (e.g. a DB fetch) and may
|
|
690
|
+
* be needed by multiple hooks in the same action invocation.
|
|
691
|
+
*
|
|
692
|
+
* Example — fetch a parent record once, reuse in both beforeUpdate and afterUpdate:
|
|
693
|
+
* const parent = await this.storeGetOrSet(opt, 'parentRecord', () =>
|
|
694
|
+
* this.getGateway('parentGw').get(params.parentId)
|
|
695
|
+
* );
|
|
696
|
+
*
|
|
697
|
+
* @param opt The BaseCoreActionsInterface opt object from any hook
|
|
698
|
+
* @param key Cache key — same string used by storeSet() / storeGet()
|
|
699
|
+
* @param factory Called on cache miss; may be async or sync
|
|
700
|
+
*/
|
|
701
|
+
protected storeGetOrSet<T>(opt: BaseCoreActionsInterface, key: string, factory: () => T | Promise<T>): Promise<T>;
|
|
662
702
|
}
|
|
663
703
|
export { BaseCore };
|
package/build/esm/BaseCore.js
CHANGED
|
@@ -588,6 +588,7 @@ class BaseCore {
|
|
|
588
588
|
setStep,
|
|
589
589
|
sameRequest,
|
|
590
590
|
hasTransaction,
|
|
591
|
+
requestStore: new Map(),
|
|
591
592
|
};
|
|
592
593
|
try {
|
|
593
594
|
// ── Step 1: Rate limiting ──────────────────────────────────────────────
|
|
@@ -1480,5 +1481,62 @@ class BaseCore {
|
|
|
1480
1481
|
}
|
|
1481
1482
|
}
|
|
1482
1483
|
}
|
|
1484
|
+
// ─── Action-scoped request store helpers ──────────────────────────────────
|
|
1485
|
+
// These helpers provide typed access to the per-action requestStore carried
|
|
1486
|
+
// in BaseCoreActionsInterface.opt. Use them in any before*, after*, validate,
|
|
1487
|
+
// or action handler to share data across hooks within a single action
|
|
1488
|
+
// invocation without adding instance properties to the subclass.
|
|
1489
|
+
/**
|
|
1490
|
+
* Stores a typed value in the action-scoped request store.
|
|
1491
|
+
*
|
|
1492
|
+
* Prefer this over opt.requestStore.set() directly — the return value
|
|
1493
|
+
* lets callers write `const v = this.storeSet(opt, key, expensiveValue)`
|
|
1494
|
+
* without a separate declaration.
|
|
1495
|
+
*
|
|
1496
|
+
* @param opt The BaseCoreActionsInterface opt object from any hook
|
|
1497
|
+
* @param key Unique string key — define keys as constants to avoid typos
|
|
1498
|
+
* @param value Any value to store; retrieved with storeGet<T>()
|
|
1499
|
+
* @returns The stored value (pass-through for convenience)
|
|
1500
|
+
*/
|
|
1501
|
+
storeSet(opt, key, value) {
|
|
1502
|
+
opt.requestStore.set(key, value);
|
|
1503
|
+
return value;
|
|
1504
|
+
}
|
|
1505
|
+
/**
|
|
1506
|
+
* Retrieves a typed value from the action-scoped request store.
|
|
1507
|
+
*
|
|
1508
|
+
* Returns undefined when the key is absent. Use opt.requestStore.has(key)
|
|
1509
|
+
* beforehand if you need to distinguish a stored undefined from a missing key.
|
|
1510
|
+
*
|
|
1511
|
+
* @param opt The BaseCoreActionsInterface opt object from any hook
|
|
1512
|
+
* @param key The key used in a prior storeSet() call
|
|
1513
|
+
*/
|
|
1514
|
+
storeGet(opt, key) {
|
|
1515
|
+
return opt.requestStore.get(key);
|
|
1516
|
+
}
|
|
1517
|
+
/**
|
|
1518
|
+
* Returns the stored value when present; otherwise calls factory(), stores
|
|
1519
|
+
* the result, and returns it.
|
|
1520
|
+
*
|
|
1521
|
+
* Use for values that are expensive to compute (e.g. a DB fetch) and may
|
|
1522
|
+
* be needed by multiple hooks in the same action invocation.
|
|
1523
|
+
*
|
|
1524
|
+
* Example — fetch a parent record once, reuse in both beforeUpdate and afterUpdate:
|
|
1525
|
+
* const parent = await this.storeGetOrSet(opt, 'parentRecord', () =>
|
|
1526
|
+
* this.getGateway('parentGw').get(params.parentId)
|
|
1527
|
+
* );
|
|
1528
|
+
*
|
|
1529
|
+
* @param opt The BaseCoreActionsInterface opt object from any hook
|
|
1530
|
+
* @param key Cache key — same string used by storeSet() / storeGet()
|
|
1531
|
+
* @param factory Called on cache miss; may be async or sync
|
|
1532
|
+
*/
|
|
1533
|
+
async storeGetOrSet(opt, key, factory) {
|
|
1534
|
+
if (opt.requestStore.has(key)) {
|
|
1535
|
+
return opt.requestStore.get(key);
|
|
1536
|
+
}
|
|
1537
|
+
const value = await factory();
|
|
1538
|
+
opt.requestStore.set(key, value);
|
|
1539
|
+
return value;
|
|
1540
|
+
}
|
|
1483
1541
|
}
|
|
1484
1542
|
export { BaseCore };
|
|
@@ -372,6 +372,20 @@ declare class BaseGateway {
|
|
|
372
372
|
* - `removeFilters` — applies declarative GatewayFilterRule array (new)
|
|
373
373
|
*/
|
|
374
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;
|
|
375
389
|
/**
|
|
376
390
|
* Transforms a params object before it is inserted into the database.
|
|
377
391
|
* Called once per object inside the `create()` loop, after the ID is generated.
|
|
@@ -671,5 +685,30 @@ declare class BaseGateway {
|
|
|
671
685
|
* `transformOnOut()`.
|
|
672
686
|
*/
|
|
673
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>;
|
|
674
713
|
}
|
|
675
714
|
export { BaseGateway };
|
package/build/esm/BaseGateway.js
CHANGED
|
@@ -2,7 +2,7 @@ import { v4 } from 'uuid';
|
|
|
2
2
|
import dayjs from 'dayjs';
|
|
3
3
|
import check from 'check-types';
|
|
4
4
|
import { camelCase, castArray, pullAll } from 'lodash';
|
|
5
|
-
import { arrToChunks, STATUSES, DateTimeHelpers, buildKey, Logger, LoggerLevels, isLogger } from '@sdflc/utils';
|
|
5
|
+
import { arrToChunks, STATUSES, DateTimeHelpers, buildKey, Logger, LoggerLevels, isLogger, camelResponse, } from '@sdflc/utils';
|
|
6
6
|
import { DataCache } from './DataCache';
|
|
7
7
|
import { FIELDS, ID_FIELD } from './constants';
|
|
8
8
|
const DEFAULT_CHUNCK_SIZE = 2500;
|
|
@@ -711,6 +711,22 @@ class BaseGateway {
|
|
|
711
711
|
filtersAppliedQty += this.applyDeclarativeRemoveFilters(query, filterParams);
|
|
712
712
|
return filtersAppliedQty;
|
|
713
713
|
}
|
|
714
|
+
/**
|
|
715
|
+
* Hook called by count() to apply custom WHERE conditions to the count query.
|
|
716
|
+
*
|
|
717
|
+
* Parallel to onListFilter() — override in subclasses that need filter logic
|
|
718
|
+
* beyond what the declarative countFilters rules can express (OR conditions,
|
|
719
|
+
* subqueries, cross-table joins, etc.).
|
|
720
|
+
*
|
|
721
|
+
* The base implementation is a no-op. Call super.onCountFilter() when
|
|
722
|
+
* overriding so future base-class logic is not silently skipped.
|
|
723
|
+
*
|
|
724
|
+
* @param query Knex query builder for the count query
|
|
725
|
+
* @param filterParams The raw filter object passed to count()
|
|
726
|
+
*/
|
|
727
|
+
onCountFilter(query, filterParams) {
|
|
728
|
+
// no-op — override in subclasses for custom count filter logic
|
|
729
|
+
}
|
|
714
730
|
// ─── Record transforms ─────────────────────────────────────────────────────
|
|
715
731
|
/**
|
|
716
732
|
* Transforms a params object before it is inserted into the database.
|
|
@@ -1304,6 +1320,70 @@ class BaseGateway {
|
|
|
1304
1320
|
}
|
|
1305
1321
|
return items.map((item) => this.transformOnOut(item));
|
|
1306
1322
|
}
|
|
1323
|
+
/**
|
|
1324
|
+
* Returns the count of non-removed rows matching the given filter.
|
|
1325
|
+
*
|
|
1326
|
+
* Applies the same soft-delete, space, and user scoping that list() uses,
|
|
1327
|
+
* ensuring count() and list() always agree on which rows are "visible" for
|
|
1328
|
+
* an identical filter. Uses COUNT(*) — no column data is read, so this is
|
|
1329
|
+
* as cheap as possible on both PostgreSQL and MS Azure SQL.
|
|
1330
|
+
*
|
|
1331
|
+
* Filter application order (mirrors list()):
|
|
1332
|
+
* 1. Soft-delete guard — WHERE Removed_By IS NULL (when hasRemovedBy)
|
|
1333
|
+
* WHERE Removed_At IS NULL (when hasRemovedAt and
|
|
1334
|
+
* not hasRemovedBy — rare, but handled for safety)
|
|
1335
|
+
* 2. Space scoping — WHERE Space_ID = context.spaceId (if hasSpace)
|
|
1336
|
+
* 3. User scoping — WHERE {filterByUserField} = context.userId (if set)
|
|
1337
|
+
* 4. onCountFilter() hook — subclass custom logic
|
|
1338
|
+
* 5. Declarative rules — countFilters when set, otherwise listFilters
|
|
1339
|
+
*
|
|
1340
|
+
* Subclasses that need count with different scoping than list have two options:
|
|
1341
|
+
* A) Set explicit countFilters in the constructor props.
|
|
1342
|
+
* B) Override onCountFilter() for logic that declarative rules cannot express.
|
|
1343
|
+
*
|
|
1344
|
+
* @param filterParams Filter object (same shape as passed to list())
|
|
1345
|
+
* @returns Row count as a number; 0 when nothing matches or on error
|
|
1346
|
+
*/
|
|
1347
|
+
async count(filterParams) {
|
|
1348
|
+
const query = this.getBuilder().count({ qty: '*' });
|
|
1349
|
+
// ── 1. Soft-delete guard ────────────────────────────────────────────────
|
|
1350
|
+
// In this codebase hasRemovedBy and hasRemovedAt are always set together
|
|
1351
|
+
// on the remove path — Removed_By is the primary sentinel. Guard on
|
|
1352
|
+
// Removed_By IS NULL first; fall back to Removed_At IS NULL for tables
|
|
1353
|
+
// that have a timestamp column but no author column (uncommon but valid).
|
|
1354
|
+
if (this.config.hasRemovedBy) {
|
|
1355
|
+
query.whereNull(`${this.config.table}.${FIELDS.REMOVED_BY}`);
|
|
1356
|
+
}
|
|
1357
|
+
else if (this.config.hasRemovedAt) {
|
|
1358
|
+
query.whereNull(`${this.config.table}.${FIELDS.REMOVED_AT}`);
|
|
1359
|
+
}
|
|
1360
|
+
// ── 2. Space scoping ────────────────────────────────────────────────────
|
|
1361
|
+
if (this.config.hasSpace && this.config.context?.spaceId) {
|
|
1362
|
+
query.where(`${this.config.table}.${FIELDS.SPACE_ID}`, this.config.context.spaceId);
|
|
1363
|
+
}
|
|
1364
|
+
// ── 3. User scoping ─────────────────────────────────────────────────────
|
|
1365
|
+
if (this.config.filterByUserField && this.config.context?.userId) {
|
|
1366
|
+
query.where(`${this.config.table}.${this.config.filterByUserField}`, this.config.context.userId);
|
|
1367
|
+
}
|
|
1368
|
+
// ── 4. Subclass hook ────────────────────────────────────────────────────
|
|
1369
|
+
this.onCountFilter(query, filterParams);
|
|
1370
|
+
// ── 5. Declarative filter rules ─────────────────────────────────────────
|
|
1371
|
+
// Fall back to listFilters when countFilters is not explicitly configured.
|
|
1372
|
+
// This means gateways that already declare listFilters get count() for free
|
|
1373
|
+
// with no changes required.
|
|
1374
|
+
const rulesToApply = this.config.countFilters ?? this.config.listFilters ?? [];
|
|
1375
|
+
for (const rule of rulesToApply) {
|
|
1376
|
+
this.applyFilterRule(query, rule, filterParams);
|
|
1377
|
+
}
|
|
1378
|
+
this.logger.debug(`Executing count on table "${this.config.table}"`);
|
|
1379
|
+
const result = camelResponse(await query);
|
|
1380
|
+
const qty = result?.[0]?.qty;
|
|
1381
|
+
if (qty == null) {
|
|
1382
|
+
this.logger.log(`Count query on "${this.config.table}" returned no result row — defaulting to 0`);
|
|
1383
|
+
return 0;
|
|
1384
|
+
}
|
|
1385
|
+
return Number(qty);
|
|
1386
|
+
}
|
|
1307
1387
|
}
|
|
1308
1388
|
export { BaseGateway };
|
|
1309
1389
|
// ─── Module-level helpers ──────────────────────────────────────────────────────
|
|
@@ -35,4 +35,30 @@ export interface BaseCoreActionsInterface {
|
|
|
35
35
|
* Object with incoming request params
|
|
36
36
|
*/
|
|
37
37
|
args?: any;
|
|
38
|
+
/**
|
|
39
|
+
* Ephemeral key-value store scoped to a single action invocation.
|
|
40
|
+
* Initialized by runAction() before any hook is called and shared
|
|
41
|
+
* across all before*, after*, validate, and action calls within
|
|
42
|
+
* that invocation.
|
|
43
|
+
*
|
|
44
|
+
* Use this instead of instance properties on subclasses to pass
|
|
45
|
+
* data between beforeXxx and afterXxx without polluting core state.
|
|
46
|
+
*
|
|
47
|
+
* Prefer the typed helpers on BaseCore — storeSet(), storeGet(), and
|
|
48
|
+
* storeGetOrSet() — over calling opt.requestStore directly, to keep
|
|
49
|
+
* call sites readable and to get compile-time type inference.
|
|
50
|
+
*
|
|
51
|
+
* Example:
|
|
52
|
+
* async beforeCreate(params, opt) {
|
|
53
|
+
* const existing = await this.getGateway().get(params.parentId);
|
|
54
|
+
* this.storeSet(opt, 'parentRecord', existing);
|
|
55
|
+
* return params;
|
|
56
|
+
* }
|
|
57
|
+
*
|
|
58
|
+
* async afterCreate(items, opt) {
|
|
59
|
+
* const parent = this.storeGet<ParentRecord>(opt, 'parentRecord');
|
|
60
|
+
* // use parent here without re-fetching
|
|
61
|
+
* }
|
|
62
|
+
*/
|
|
63
|
+
requestStore: Map<string, unknown>;
|
|
38
64
|
}
|
|
@@ -165,4 +165,21 @@ export interface BaseGatewayPropsInterface extends CacheInterface {
|
|
|
165
165
|
* ]
|
|
166
166
|
*/
|
|
167
167
|
removeFilters?: GatewayFilterRule[];
|
|
168
|
+
/**
|
|
169
|
+
* Declarative WHERE rules applied by count() after base scoping logic.
|
|
170
|
+
*
|
|
171
|
+
* When not explicitly set, count() falls back to listFilters — in most
|
|
172
|
+
* cases count and list should be scoped identically for the same filter
|
|
173
|
+
* params. Set countFilters explicitly only when count needs different
|
|
174
|
+
* scoping than list (e.g. counting across statuses that list excludes).
|
|
175
|
+
*
|
|
176
|
+
* All filter types are supported ('search', 'dateRange', 'nullableDateRange'
|
|
177
|
+
* included) — count() is a read operation, same as list().
|
|
178
|
+
*
|
|
179
|
+
* Example:
|
|
180
|
+
* countFilters: [
|
|
181
|
+
* { field: 'partyId', column: 'Party_Guest.Party_ID', type: 'array' },
|
|
182
|
+
* ]
|
|
183
|
+
*/
|
|
184
|
+
countFilters?: GatewayFilterRule[];
|
|
168
185
|
}
|
|
@@ -35,4 +35,30 @@ export interface BaseCoreActionsInterface {
|
|
|
35
35
|
* Object with incoming request params
|
|
36
36
|
*/
|
|
37
37
|
args?: any;
|
|
38
|
+
/**
|
|
39
|
+
* Ephemeral key-value store scoped to a single action invocation.
|
|
40
|
+
* Initialized by runAction() before any hook is called and shared
|
|
41
|
+
* across all before*, after*, validate, and action calls within
|
|
42
|
+
* that invocation.
|
|
43
|
+
*
|
|
44
|
+
* Use this instead of instance properties on subclasses to pass
|
|
45
|
+
* data between beforeXxx and afterXxx without polluting core state.
|
|
46
|
+
*
|
|
47
|
+
* Prefer the typed helpers on BaseCore — storeSet(), storeGet(), and
|
|
48
|
+
* storeGetOrSet() — over calling opt.requestStore directly, to keep
|
|
49
|
+
* call sites readable and to get compile-time type inference.
|
|
50
|
+
*
|
|
51
|
+
* Example:
|
|
52
|
+
* async beforeCreate(params, opt) {
|
|
53
|
+
* const existing = await this.getGateway().get(params.parentId);
|
|
54
|
+
* this.storeSet(opt, 'parentRecord', existing);
|
|
55
|
+
* return params;
|
|
56
|
+
* }
|
|
57
|
+
*
|
|
58
|
+
* async afterCreate(items, opt) {
|
|
59
|
+
* const parent = this.storeGet<ParentRecord>(opt, 'parentRecord');
|
|
60
|
+
* // use parent here without re-fetching
|
|
61
|
+
* }
|
|
62
|
+
*/
|
|
63
|
+
requestStore: Map<string, unknown>;
|
|
38
64
|
}
|
|
@@ -165,4 +165,21 @@ export interface BaseGatewayPropsInterface extends CacheInterface {
|
|
|
165
165
|
* ]
|
|
166
166
|
*/
|
|
167
167
|
removeFilters?: GatewayFilterRule[];
|
|
168
|
+
/**
|
|
169
|
+
* Declarative WHERE rules applied by count() after base scoping logic.
|
|
170
|
+
*
|
|
171
|
+
* When not explicitly set, count() falls back to listFilters — in most
|
|
172
|
+
* cases count and list should be scoped identically for the same filter
|
|
173
|
+
* params. Set countFilters explicitly only when count needs different
|
|
174
|
+
* scoping than list (e.g. counting across statuses that list excludes).
|
|
175
|
+
*
|
|
176
|
+
* All filter types are supported ('search', 'dateRange', 'nullableDateRange'
|
|
177
|
+
* included) — count() is a read operation, same as list().
|
|
178
|
+
*
|
|
179
|
+
* Example:
|
|
180
|
+
* countFilters: [
|
|
181
|
+
* { field: 'partyId', column: 'Party_Guest.Party_ID', type: 'array' },
|
|
182
|
+
* ]
|
|
183
|
+
*/
|
|
184
|
+
countFilters?: GatewayFilterRule[];
|
|
168
185
|
}
|