@sdflc/backend-helpers 1.0.114 → 1.0.115
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 +274 -121
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @sdflc/backend-helpers
|
|
2
2
|
|
|
3
|
-
A comprehensive backend framework for Node.js applications providing database access, authentication, caching, GraphQL resolver helpers, REST controllers, CLI utilities, and migration tools.
|
|
3
|
+
A comprehensive backend framework for Node.js applications providing database access, authentication, caching, IP-based rate limiting, GraphQL resolver helpers, REST controllers, CLI utilities, and migration tools.
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
@@ -26,6 +26,15 @@ A comprehensive backend framework for Node.js applications providing database ac
|
|
|
26
26
|
- [BaseController](#basecontroller)
|
|
27
27
|
- [BaseRestApiCrudController](#baserestapicrudcontroller)
|
|
28
28
|
- [BaseExternalApiGateway](#baseexternalapigatewayx)
|
|
29
|
+
- [IP rate limiting](#ip-rate-limiting)
|
|
30
|
+
- [How it works](#how-it-works)
|
|
31
|
+
- [Setup](#setup)
|
|
32
|
+
- [Global tier](#global-tier)
|
|
33
|
+
- [Core-level rules](#core-level-rules)
|
|
34
|
+
- [Action-level rules](#action-level-rules)
|
|
35
|
+
- [Per-call override](#per-call-override)
|
|
36
|
+
- [Disabling rate limiting](#disabling-rate-limiting)
|
|
37
|
+
- [Custom limiter](#custom-limiter)
|
|
29
38
|
- [Database](#database)
|
|
30
39
|
- [Database class](#database-class)
|
|
31
40
|
- [DataCache and custom loaders](#datacache-and-custom-loaders)
|
|
@@ -74,9 +83,9 @@ Application layer → GraphQL resolvers / REST controllers / CLI
|
|
|
74
83
|
transform inputs before passing them to cores.
|
|
75
84
|
|
|
76
85
|
Business layer → Core classes (BaseCore subclasses)
|
|
77
|
-
Manage transactions, handle request-level authentication
|
|
78
|
-
|
|
79
|
-
responses into a consistent OpResult shape.
|
|
86
|
+
Manage transactions, handle request-level authentication,
|
|
87
|
+
validation, IP rate limiting, enforce business rules,
|
|
88
|
+
and normalise responses into a consistent OpResult shape.
|
|
80
89
|
|
|
81
90
|
Data layer → Gateway classes (BaseGateway subclasses)
|
|
82
91
|
Perform CRUD operations on database tables, run complex
|
|
@@ -269,6 +278,8 @@ export const redisClient = config.redisHost
|
|
|
269
278
|
|
|
270
279
|
> The client is created but **not connected** — call `await redisClient.connect()` during app or CLI startup. This allows the client to be created early and connected at a controlled point.
|
|
271
280
|
|
|
281
|
+
The same `redisClient` instance is used for both DataLoader caching (via gateways) and IP rate limiting (via `createContextDefault`). Pass it once — the library routes it to both uses automatically.
|
|
282
|
+
|
|
272
283
|
---
|
|
273
284
|
|
|
274
285
|
### Knex handle
|
|
@@ -300,7 +311,7 @@ export default knex({
|
|
|
300
311
|
|
|
301
312
|
### Context
|
|
302
313
|
|
|
303
|
-
The context factory creates a fresh `ApiContext` for every request. All gateways and cores are instantiated here. The same factory is used by GraphQL, REST, and CLI
|
|
314
|
+
The context factory creates a fresh `ApiContext` for every request. All gateways and cores are instantiated here. The same factory is used by GraphQL, REST, and CLI.
|
|
304
315
|
|
|
305
316
|
```typescript
|
|
306
317
|
// src/context.ts
|
|
@@ -331,6 +342,12 @@ export const createContext = async (args: any) => {
|
|
|
331
342
|
ignoreExpiration: false,
|
|
332
343
|
ignoreNotBefore: false,
|
|
333
344
|
},
|
|
345
|
+
// Pass redisClient to enable IP rate limiting automatically.
|
|
346
|
+
// An IpRateLimiter instance is constructed once here and shared
|
|
347
|
+
// across all cores for the lifetime of this request.
|
|
348
|
+
redisClient,
|
|
349
|
+
// Optional: cap every IP at 300 requests per minute across all cores.
|
|
350
|
+
globalRateLimit: { limit: 300, windowSec: 60 },
|
|
334
351
|
// Provide extra props to every gateway constructor
|
|
335
352
|
getGatewayContext: () => ({
|
|
336
353
|
redisClient,
|
|
@@ -349,6 +366,16 @@ export const createContext = async (args: any) => {
|
|
|
349
366
|
};
|
|
350
367
|
```
|
|
351
368
|
|
|
369
|
+
#### `createContextDefault` options
|
|
370
|
+
|
|
371
|
+
All options from the original factory plus the new rate-limiting options:
|
|
372
|
+
|
|
373
|
+
| Option | Type | Description |
|
|
374
|
+
| ----------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
375
|
+
| `redisClient` | `any \| null` | Redis client for the built-in `IpRateLimiter`. If provided and no `rateLimiter` is set, an `IpRateLimiter` is constructed automatically and placed on `context.rateLimiter`. |
|
|
376
|
+
| `rateLimiter` | `RateLimiterInterface \| null` | Custom rate-limiter instance. Overrides `redisClient`. Set to `null` to disable rate limiting explicitly. |
|
|
377
|
+
| `globalRateLimit` | `RateLimitRule` | Service-wide rule applied as the global tier to every `runAction` call across all cores. |
|
|
378
|
+
|
|
352
379
|
---
|
|
353
380
|
|
|
354
381
|
### Express app
|
|
@@ -440,12 +467,7 @@ const configureApp = async (app: any) => {
|
|
|
440
467
|
|
|
441
468
|
await apolloServer.start();
|
|
442
469
|
|
|
443
|
-
app.use(
|
|
444
|
-
config.graphqlUrl,
|
|
445
|
-
cors(corsOptions),
|
|
446
|
-
express.json(),
|
|
447
|
-
expressMiddleware(apolloServer, { context: createContext }),
|
|
448
|
-
);
|
|
470
|
+
app.use(config.graphqlUrl, cors(corsOptions), expressMiddleware(apolloServer, { context: createContext }));
|
|
449
471
|
|
|
450
472
|
// 404 handler
|
|
451
473
|
app.use((req: any, res: any) => {
|
|
@@ -492,18 +514,36 @@ export default configureApp;
|
|
|
492
514
|
|
|
493
515
|
The request context object shared across all layers. Created once per request — or once per CLI invocation.
|
|
494
516
|
|
|
495
|
-
| Field
|
|
496
|
-
|
|
|
497
|
-
| `requestId`
|
|
498
|
-
| `cores`
|
|
499
|
-
| `gateways`
|
|
500
|
-
| `
|
|
501
|
-
| `
|
|
502
|
-
| `
|
|
503
|
-
| `
|
|
504
|
-
| `
|
|
505
|
-
| `
|
|
506
|
-
| `
|
|
517
|
+
| Field | Type | Description |
|
|
518
|
+
| -------------------- | ----------------------- | ----------------------------------------------------------------------------------------------- |
|
|
519
|
+
| `requestId` | `string` | UUID generated per request |
|
|
520
|
+
| `cores` | `Record<string, any>` | All registered core instances (camelCase keys) |
|
|
521
|
+
| `gateways` | `Record<string, any>` | All registered gateway instances (camelCase keys) |
|
|
522
|
+
| `usedKeyPrefixes` | `Record<string, any>` | Tracks gateway key prefixes to detect collisions |
|
|
523
|
+
| `db` | `Database` | Shared database instance |
|
|
524
|
+
| `req` / `res` | `any` | Express request/response objects |
|
|
525
|
+
| `headers` | `Record<string, any>` | Raw request headers |
|
|
526
|
+
| `cookies` | `Record<string, any>` | Parsed request cookies |
|
|
527
|
+
| `spaceId` | `string?` | From request headers or JWT token |
|
|
528
|
+
| `apiKey` | `string?` | From `x-api-key` header |
|
|
529
|
+
| `managementApiKey` | `string?` | From management API key header |
|
|
530
|
+
| `ipAddress` | `string?` | Client IP address — used by the rate limiter |
|
|
531
|
+
| `authorization` | `string?` | Bearer token stripped from Authorization header |
|
|
532
|
+
| `fingerprint` | `string?` | CSRF fingerprint from cookie or header |
|
|
533
|
+
| `acceptLanguage` | `string?` | Raw `Accept-Language` header value |
|
|
534
|
+
| `languages` | `string[]?` | Parsed language preference list |
|
|
535
|
+
| `requestedLang` | `string?` | Resolved language for the request (default `'en'`) |
|
|
536
|
+
| `userAgent` | `string?` | `User-Agent` header |
|
|
537
|
+
| `referer` | `string?` | `Referer` header |
|
|
538
|
+
| `authorizationToken` | `string?` | Raw authorization token passed explicitly |
|
|
539
|
+
| `isExternalDb` | `boolean?` | True when a pre-built `db` was passed in |
|
|
540
|
+
| `userId` | `string?` | Populated after successful authentication |
|
|
541
|
+
| `accountId` | `string?` | Populated after successful authentication |
|
|
542
|
+
| `roleId` | `string?` | Populated after successful authentication |
|
|
543
|
+
| `isSuperAdmin` | `boolean?` | True when `roleId === 'superadmin'` |
|
|
544
|
+
| `lang` | `string?` | Resolved language from token or header |
|
|
545
|
+
| `rateLimiter` | `RateLimiterInterface?` | App-level rate-limiter singleton — set by `createContextDefault` when `redisClient` is provided |
|
|
546
|
+
| `globalRateLimit` | `RateLimitRule?` | Service-wide rate-limit rule applied to all cores |
|
|
507
547
|
|
|
508
548
|
---
|
|
509
549
|
|
|
@@ -553,60 +593,17 @@ class NoteCore extends AppCore {
|
|
|
553
593
|
remove: 'removing a note',
|
|
554
594
|
removeMany: 'removing multiple notes',
|
|
555
595
|
},
|
|
596
|
+
// Rate limiting — tighten create, leave reads unrestricted
|
|
597
|
+
rateLimit: { limit: 60, windowSec: 60 },
|
|
598
|
+
rateLimitOnAction: {
|
|
599
|
+
list: false,
|
|
600
|
+
get: false,
|
|
601
|
+
create: { limit: 10, windowSec: 60 },
|
|
602
|
+
},
|
|
556
603
|
});
|
|
557
604
|
}
|
|
558
605
|
|
|
559
|
-
|
|
560
|
-
return {
|
|
561
|
-
...super.getValidators(),
|
|
562
|
-
...validators,
|
|
563
|
-
};
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
// Scope all list queries to the current user
|
|
567
|
-
public async beforeList(args: any, opt?: BaseCoreActionsInterface): Promise<any> {
|
|
568
|
-
const { filter } = args || {};
|
|
569
|
-
const { userId } = this.getContext();
|
|
570
|
-
|
|
571
|
-
if (!userId) {
|
|
572
|
-
return OpResult.ok([]);
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
return { ...args, filter: { ...filter, userId } };
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
// Enforce ownership — return null so core responds with NOT_FOUND
|
|
579
|
-
public async afterGet(item: any, opt?: BaseCoreActionsInterface): Promise<any> {
|
|
580
|
-
if (!item) return item;
|
|
581
|
-
|
|
582
|
-
if (item.userId !== this.getContext().userId) {
|
|
583
|
-
return null;
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
return this.processItemOnOut(item, opt);
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
// Inject userId on create
|
|
590
|
-
public async beforeCreate(params: any, opt?: BaseCoreActionsInterface): Promise<any> {
|
|
591
|
-
return { ...params, userId: this.getContext().userId };
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
// Inject userId into where clause to prevent cross-user updates
|
|
595
|
-
public async beforeUpdate(params: any, opt?: BaseCoreActionsInterface): Promise<any> {
|
|
596
|
-
const { args } = opt || {};
|
|
597
|
-
const { where } = args || {};
|
|
598
|
-
|
|
599
|
-
if (where) {
|
|
600
|
-
where.userId = this.getContext().userId;
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
return params;
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
// Prevent removing other users' notes
|
|
607
|
-
public async beforeRemove(where: any, opt?: BaseCoreActionsInterface): Promise<any> {
|
|
608
|
-
return { ...where, userId: this.getContext().userId };
|
|
609
|
-
}
|
|
606
|
+
// ... validators, hooks, etc.
|
|
610
607
|
}
|
|
611
608
|
|
|
612
609
|
export { NoteCore };
|
|
@@ -866,6 +863,178 @@ await gw.chargeCard(1000, 'usd');
|
|
|
866
863
|
|
|
867
864
|
---
|
|
868
865
|
|
|
866
|
+
## IP rate limiting
|
|
867
|
+
|
|
868
|
+
### How it works
|
|
869
|
+
|
|
870
|
+
Rate limiting is built into `BaseCore` and runs automatically on every `runAction` call — before the database transaction is opened and before authentication. This protects auth endpoints from brute-force without any DB overhead.
|
|
871
|
+
|
|
872
|
+
The implementation uses two independent tiers, both of which must pass for a request to proceed. Each tier maintains its own Redis counter keyed on `(space, scope, action, ip)`.
|
|
873
|
+
|
|
874
|
+
**Global tier** — a service-wide ceiling applied to every core and every action. Cannot be opted out by core or action configuration. Guards the whole service from a flood regardless of which endpoint is targeted.
|
|
875
|
+
|
|
876
|
+
**Core-or-action tier** — a more specific limit scoped to a core or a single action. Core and action rules are **mutually exclusive**: an action rule replaces the core rule for that action so that loosening a limit actually raises it — the core counter will not silently block first.
|
|
877
|
+
|
|
878
|
+
Resolution for the core-or-action tier (first defined value wins):
|
|
879
|
+
|
|
880
|
+
1. `CoreActionInterface.rateLimit` — per-call override in `runAction()`
|
|
881
|
+
2. `BaseCorePropsInterface.rateLimitOnAction[actionName]` — per-action props
|
|
882
|
+
3. `BaseCorePropsInterface.rateLimit` — core-level default
|
|
883
|
+
4. Nothing — tier is skipped
|
|
884
|
+
|
|
885
|
+
Using `false` at steps 1 or 2 disables the core-or-action tier for that action entirely so only the global tier applies. `false` never suppresses the global tier.
|
|
886
|
+
|
|
887
|
+
Blocked requests receive `OP_RESULT_CODES.TOO_MANY_REQUESTS` (429) with a human-readable message including the time until the window resets.
|
|
888
|
+
|
|
889
|
+
Redis errors are swallowed silently — the limiter allows requests through rather than taking down an endpoint. If Redis is not configured, rate limiting is completely skipped with zero overhead.
|
|
890
|
+
|
|
891
|
+
---
|
|
892
|
+
|
|
893
|
+
### Setup
|
|
894
|
+
|
|
895
|
+
The minimum to enable rate limiting is passing `redisClient` to `createContextDefault`. An `IpRateLimiter` instance is constructed once per request context and shared across all cores automatically — no per-core wiring needed.
|
|
896
|
+
|
|
897
|
+
```typescript
|
|
898
|
+
// src/context.ts
|
|
899
|
+
export const createContext = async (args: any) => {
|
|
900
|
+
return createContextDefault({
|
|
901
|
+
// ...existing options...
|
|
902
|
+
redisClient, // enables rate limiting
|
|
903
|
+
globalRateLimit: { limit: 300, windowSec: 60 }, // optional service-wide cap
|
|
904
|
+
});
|
|
905
|
+
};
|
|
906
|
+
```
|
|
907
|
+
|
|
908
|
+
That is the only change needed to get rate limiting running across all cores. Per-core and per-action rules are additive on top.
|
|
909
|
+
|
|
910
|
+
---
|
|
911
|
+
|
|
912
|
+
### Global tier
|
|
913
|
+
|
|
914
|
+
Set `globalRateLimit` on the context to cap every IP across all cores and all actions. This is the flood guard — it runs regardless of what the core or action configures.
|
|
915
|
+
|
|
916
|
+
```typescript
|
|
917
|
+
createContextDefault({
|
|
918
|
+
redisClient,
|
|
919
|
+
globalRateLimit: { limit: 500, windowSec: 60 }, // 500 req/min per IP, service-wide
|
|
920
|
+
});
|
|
921
|
+
```
|
|
922
|
+
|
|
923
|
+
The global tier has no opt-out. If you need an endpoint to be completely unmetered, do not set `globalRateLimit`.
|
|
924
|
+
|
|
925
|
+
---
|
|
926
|
+
|
|
927
|
+
### Core-level rules
|
|
928
|
+
|
|
929
|
+
Add `rateLimit` to a core's constructor props to apply a default rule to every action in that core. Individual actions can override or disable it via `rateLimitOnAction`.
|
|
930
|
+
|
|
931
|
+
```typescript
|
|
932
|
+
class AuthCore extends AppCore {
|
|
933
|
+
constructor(props: BaseCorePropsInterface) {
|
|
934
|
+
super({
|
|
935
|
+
...props,
|
|
936
|
+
rateLimit: { limit: 30, windowSec: 60 }, // 30 req/min for all auth actions
|
|
937
|
+
rateLimitOnAction: {
|
|
938
|
+
list: false, // no core-tier limit for list
|
|
939
|
+
get: false, // no core-tier limit for get
|
|
940
|
+
create: { limit: 5, windowSec: 300 }, // tighter for sign-up (replaces core rule)
|
|
941
|
+
},
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
```
|
|
946
|
+
|
|
947
|
+
`rateLimitOnAction` values:
|
|
948
|
+
|
|
949
|
+
| Value | Effect |
|
|
950
|
+
| --------------- | -------------------------------------------------------------- |
|
|
951
|
+
| `RateLimitRule` | Replaces the core rule for this action (action wins) |
|
|
952
|
+
| `false` | Disables the core-or-action tier for this action (global only) |
|
|
953
|
+
| `undefined` | Falls back to the core-level `rateLimit` default |
|
|
954
|
+
|
|
955
|
+
---
|
|
956
|
+
|
|
957
|
+
### Action-level rules
|
|
958
|
+
|
|
959
|
+
Pass `rateLimit` directly to `runAction()` for a one-off rule on a specific call. This is the highest-priority override and replaces any `rateLimitOnAction` or `rateLimit` configured in props for that call.
|
|
960
|
+
|
|
961
|
+
```typescript
|
|
962
|
+
return this.runAction({
|
|
963
|
+
args,
|
|
964
|
+
doAuth: true,
|
|
965
|
+
hasTransaction: true,
|
|
966
|
+
actionName: 'signIn',
|
|
967
|
+
rateLimit: { limit: 5, windowSec: 300 }, // 5 attempts per 5 minutes
|
|
968
|
+
doingWhat: 'signing in',
|
|
969
|
+
action: async (args, opt) => {
|
|
970
|
+
/* ... */
|
|
971
|
+
},
|
|
972
|
+
});
|
|
973
|
+
```
|
|
974
|
+
|
|
975
|
+
---
|
|
976
|
+
|
|
977
|
+
### Disabling rate limiting
|
|
978
|
+
|
|
979
|
+
Set `rateLimit: false` at the call site or in `rateLimitOnAction` to disable the core-or-action tier for a specific action. The global tier still runs.
|
|
980
|
+
|
|
981
|
+
```typescript
|
|
982
|
+
// Disable core-tier for an internal helper action:
|
|
983
|
+
return this.runAction({
|
|
984
|
+
args,
|
|
985
|
+
rateLimit: false,
|
|
986
|
+
hasTransaction: false,
|
|
987
|
+
doingWhat: 'fetching internal config',
|
|
988
|
+
action: async (args, opt) => {
|
|
989
|
+
/* ... */
|
|
990
|
+
},
|
|
991
|
+
});
|
|
992
|
+
|
|
993
|
+
// Disable core-tier for specific actions in props:
|
|
994
|
+
super({
|
|
995
|
+
...props,
|
|
996
|
+
rateLimit: { limit: 60, windowSec: 60 },
|
|
997
|
+
rateLimitOnAction: {
|
|
998
|
+
list: false, // reads are unrestricted at core tier
|
|
999
|
+
get: false,
|
|
1000
|
+
},
|
|
1001
|
+
});
|
|
1002
|
+
```
|
|
1003
|
+
|
|
1004
|
+
To disable rate limiting entirely for a core (including ignoring `context.rateLimiter`), pass `rateLimiter: null` in the core's props:
|
|
1005
|
+
|
|
1006
|
+
```typescript
|
|
1007
|
+
super({
|
|
1008
|
+
...props,
|
|
1009
|
+
rateLimiter: null, // this core is completely exempt from rate limiting
|
|
1010
|
+
});
|
|
1011
|
+
```
|
|
1012
|
+
|
|
1013
|
+
---
|
|
1014
|
+
|
|
1015
|
+
### Custom limiter
|
|
1016
|
+
|
|
1017
|
+
To use a different rate-limiting backend (e.g. in-memory for tests, DynamoDB for Lambda), implement `RateLimiterInterface` and pass it via `rateLimiter` in `createContextDefault` or in per-core props.
|
|
1018
|
+
|
|
1019
|
+
```typescript
|
|
1020
|
+
import { RateLimiterInterface, RateLimitCheckArgs, RateLimitResult } from '@sdflc/backend-helpers';
|
|
1021
|
+
|
|
1022
|
+
class NoOpRateLimiter implements RateLimiterInterface {
|
|
1023
|
+
async check(_args: RateLimitCheckArgs): Promise<RateLimitResult> {
|
|
1024
|
+
return { blocked: false, count: 0, ttlSec: -1 };
|
|
1025
|
+
}
|
|
1026
|
+
async reset(_args: Pick<RateLimitCheckArgs, 'action' | 'ip' | 'spaceId'>): Promise<void> {}
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
// In tests — disable all rate limiting:
|
|
1030
|
+
createContextDefault({
|
|
1031
|
+
rateLimiter: new NoOpRateLimiter(),
|
|
1032
|
+
// no redisClient needed
|
|
1033
|
+
});
|
|
1034
|
+
```
|
|
1035
|
+
|
|
1036
|
+
---
|
|
1037
|
+
|
|
869
1038
|
## Database
|
|
870
1039
|
|
|
871
1040
|
### Database class
|
|
@@ -1154,14 +1323,6 @@ import knexHandle from '../../knexHandle';
|
|
|
1154
1323
|
import { logger } from '../../logger';
|
|
1155
1324
|
import { redisClient } from '../../redisClient';
|
|
1156
1325
|
|
|
1157
|
-
/**
|
|
1158
|
-
* Builds a synthetic context for CLI commands.
|
|
1159
|
-
*
|
|
1160
|
-
* CLI commands do not have an HTTP request, so we construct a minimal req
|
|
1161
|
-
* object with the headers that createContextDefault reads for space/auth
|
|
1162
|
-
* resolution. Since CLI commands typically run with elevated access, we
|
|
1163
|
-
* bypass JWT auth by providing the interservice API key directly.
|
|
1164
|
-
*/
|
|
1165
1326
|
const getContext = () =>
|
|
1166
1327
|
createContext({
|
|
1167
1328
|
res: {},
|
|
@@ -1176,10 +1337,7 @@ const getContext = () =>
|
|
|
1176
1337
|
},
|
|
1177
1338
|
});
|
|
1178
1339
|
|
|
1179
|
-
// ─── Commands ────────────────────────────────────────────────────────────────
|
|
1180
|
-
|
|
1181
1340
|
const resetDb = () => {
|
|
1182
|
-
// dbReset is a standalone helper — does not need a context
|
|
1183
1341
|
dbReset(knexHandle, config).then(() => knexHandle.destroy());
|
|
1184
1342
|
};
|
|
1185
1343
|
|
|
@@ -1199,7 +1357,6 @@ const syncExternalData = async () => {
|
|
|
1199
1357
|
const context = await getContext();
|
|
1200
1358
|
|
|
1201
1359
|
try {
|
|
1202
|
-
// Connect Redis if available — some core operations use it for locking
|
|
1203
1360
|
if (redisClient) {
|
|
1204
1361
|
await redisClient.connect();
|
|
1205
1362
|
}
|
|
@@ -1216,8 +1373,6 @@ const syncExternalData = async () => {
|
|
|
1216
1373
|
}
|
|
1217
1374
|
};
|
|
1218
1375
|
|
|
1219
|
-
// ─── Command registration ─────────────────────────────────────────────────────
|
|
1220
|
-
|
|
1221
1376
|
yargs(process.argv.splice(2))
|
|
1222
1377
|
.command('reset', 'Wipes the database, runs all migrations, and seeds', () => {}, resetDb)
|
|
1223
1378
|
.command('recalculate', 'Recalculates all stats and derived data', () => {}, recalculateStats)
|
|
@@ -1229,15 +1384,15 @@ yargs(process.argv.splice(2))
|
|
|
1229
1384
|
|
|
1230
1385
|
### Key points
|
|
1231
1386
|
|
|
1232
|
-
**Context reuse** — the same `createContext()` factory used by GraphQL and REST is used here
|
|
1387
|
+
**Context reuse** — the same `createContext()` factory used by GraphQL and REST is used here with a synthetic `req` object. All authentication, gateway initialisation, Redis, and rate-limiting wiring happens identically.
|
|
1233
1388
|
|
|
1234
|
-
**Interservice API key** — CLI commands
|
|
1389
|
+
**Interservice API key** — CLI commands bypass JWT auth by providing `interserviceApiKey` in the synthetic headers.
|
|
1235
1390
|
|
|
1236
|
-
**Redis** —
|
|
1391
|
+
**Redis** — connect `redisClient` before calling core methods that require it. Rate limiting is also active for CLI calls if `redisClient` is configured — this is usually desirable but can be bypassed by passing `rateLimiter: null` to `createContextDefault` in your CLI's `createContext` factory if needed.
|
|
1237
1392
|
|
|
1238
|
-
**Process exit** — CLI commands should call `process.exit(0)` in a `finally` block to
|
|
1393
|
+
**Process exit** — CLI commands should call `process.exit(0)` in a `finally` block to close open database connections and Redis clients cleanly.
|
|
1239
1394
|
|
|
1240
|
-
**Database reset** — `dbReset`
|
|
1395
|
+
**Database reset** — `dbReset` operates directly on a Knex handle without going through the context.
|
|
1241
1396
|
|
|
1242
1397
|
---
|
|
1243
1398
|
|
|
@@ -1424,31 +1579,29 @@ ORDER_BYS.DESC; // 'desc'
|
|
|
1424
1579
|
|
|
1425
1580
|
## Interfaces reference
|
|
1426
1581
|
|
|
1427
|
-
| Interface | Description
|
|
1428
|
-
| ----------------------------------------- |
|
|
1429
|
-
| `ApiContext` | Request context object shape
|
|
1430
|
-
| `ApiContextInterface` | Arguments for `createApiContext()`
|
|
1431
|
-
| `BaseCorePropsInterface` | Constructor props for `BaseCore` subclasses
|
|
1432
|
-
| `
|
|
1433
|
-
| `
|
|
1434
|
-
| `
|
|
1435
|
-
| `
|
|
1436
|
-
| `
|
|
1437
|
-
| `
|
|
1438
|
-
| `
|
|
1439
|
-
| `
|
|
1440
|
-
| `
|
|
1441
|
-
| `
|
|
1442
|
-
| `
|
|
1443
|
-
| `
|
|
1444
|
-
| `
|
|
1445
|
-
| `
|
|
1446
|
-
| `
|
|
1447
|
-
| `
|
|
1448
|
-
| `
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
MIT
|
|
1582
|
+
| Interface | Description |
|
|
1583
|
+
| ----------------------------------------- | -------------------------------------------------------------------------------- |
|
|
1584
|
+
| `ApiContext` | Request context object shape |
|
|
1585
|
+
| `ApiContextInterface` | Arguments for `createApiContext()` |
|
|
1586
|
+
| `BaseCorePropsInterface` | Constructor props for `BaseCore` subclasses |
|
|
1587
|
+
| `BaseCoreRateLimitOnActionInterface` | Per-action rate-limit rule map used in `BaseCorePropsInterface` |
|
|
1588
|
+
| `BaseGatewayPropsInterface` | Constructor props for `BaseGateway` subclasses |
|
|
1589
|
+
| `BaseExternalApiGatewayPropsInterface` | Constructor props for `BaseExternalApiGateway` |
|
|
1590
|
+
| `BaseRestApiCrudControllerPropsInterface` | Constructor props for `BaseRestApiCrudController` |
|
|
1591
|
+
| `BuildDefaultResolvers` | Arguments for `buildDefaultResolvers()` |
|
|
1592
|
+
| `BuildConfigOptions` | Options for `buildConfig()` |
|
|
1593
|
+
| `DatabaseOptions` | Options for `Database` constructor |
|
|
1594
|
+
| `DatabaseReadInterface` | Arguments for `Database.read()` |
|
|
1595
|
+
| `CacheInterface` | Config for `DataCache` (without request context) |
|
|
1596
|
+
| `DataCachePropsInterface` | Full props for `DataCache` including request context |
|
|
1597
|
+
| `LoaderInterface` | Interface for custom loaders (`load`, `loadMany`, `clear`, `prime`) |
|
|
1598
|
+
| `RateLimitRule` | Rate-limit rule shape: `{ limit, windowSec, action? }` |
|
|
1599
|
+
| `RateLimiterInterface` | Structural interface for custom rate-limiter implementations |
|
|
1600
|
+
| `IpRateLimiter` | Built-in Redis-backed rate limiter; constructed automatically from `redisClient` |
|
|
1601
|
+
| `CoreActionInterface` | Arguments for `BaseCore.runAction()` including `tryAuth` and `rateLimit` |
|
|
1602
|
+
| `CreateUserTokenArgs` | Options for `createUserToken()` |
|
|
1603
|
+
| `VerifyUserTokenArgs` | Options for `verifyUserToken()` |
|
|
1604
|
+
| `UserTokenParams` | JWT payload structure |
|
|
1605
|
+
| `DownloadFileArgs` | Arguments for `downloadFile()` |
|
|
1606
|
+
| `DbFieldAddDefaultInterface` | Options for `dbFieldAddDefaults()` |
|
|
1607
|
+
| `ListArgsInterface` | Standard list operation arguments |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sdflc/backend-helpers",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.115",
|
|
4
4
|
"description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"exports": {
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"postversion": "git push && git push --tags"
|
|
30
30
|
},
|
|
31
31
|
"author": "Sergey Demidenko",
|
|
32
|
-
"license": "
|
|
32
|
+
"license": "MIT",
|
|
33
33
|
"devDependencies": {
|
|
34
34
|
"@eslint/js": "^10.0.1",
|
|
35
35
|
"@types/bcrypt": "^6.0.0",
|