@sdflc/backend-helpers 1.0.112 → 1.0.113

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.
Files changed (206) hide show
  1. package/README.md +1422 -146
  2. package/build/BaseController.d.ts +20 -0
  3. package/build/BaseController.js +64 -0
  4. package/build/BaseCore.d.ts +470 -33
  5. package/build/BaseCore.js +608 -127
  6. package/build/BaseExternalApiGateway.d.ts +16 -0
  7. package/build/BaseExternalApiGateway.js +54 -0
  8. package/build/BaseGateway.d.ts +455 -17
  9. package/build/BaseGateway.js +502 -56
  10. package/build/BaseRestApiCrudController.d.ts +37 -0
  11. package/build/BaseRestApiCrudController.js +134 -0
  12. package/build/DataCache.d.ts +116 -5
  13. package/build/DataCache.js +144 -22
  14. package/build/Database.d.ts +165 -4
  15. package/build/Database.js +224 -51
  16. package/build/DbMigratorAndSeeder.d.ts +127 -26
  17. package/build/DbMigratorAndSeeder.js +180 -69
  18. package/build/RedisDataLoader.d.ts +144 -21
  19. package/build/RedisDataLoader.js +178 -49
  20. package/build/apiContext.d.ts +0 -8
  21. package/build/apiContext.js +12 -27
  22. package/build/checkItHelpers.d.ts +32 -0
  23. package/build/checkItHelpers.js +73 -7
  24. package/build/commonValidators.d.ts +107 -16
  25. package/build/commonValidators.js +211 -106
  26. package/build/configBuilder.d.ts +23 -0
  27. package/build/configBuilder.js +73 -0
  28. package/build/constants.d.ts +134 -17
  29. package/build/constants.js +95 -15
  30. package/build/dbHelpers.d.ts +89 -29
  31. package/build/dbHelpers.js +175 -86
  32. package/build/dbSeeder.d.ts +10 -1
  33. package/build/dbSeeder.js +80 -15
  34. package/build/dbTableHelpers.d.ts +122 -5
  35. package/build/dbTableHelpers.js +151 -13
  36. package/build/downloadHelpers.d.ts +24 -1
  37. package/build/downloadHelpers.js +51 -21
  38. package/build/esm/BaseController.d.ts +20 -0
  39. package/build/esm/BaseController.js +58 -0
  40. package/build/esm/BaseCore.d.ts +470 -33
  41. package/build/esm/BaseCore.js +599 -118
  42. package/build/esm/BaseExternalApiGateway.d.ts +16 -0
  43. package/build/esm/BaseExternalApiGateway.js +48 -0
  44. package/build/esm/BaseGateway.d.ts +455 -17
  45. package/build/esm/BaseGateway.js +503 -57
  46. package/build/esm/BaseRestApiCrudController.d.ts +37 -0
  47. package/build/esm/BaseRestApiCrudController.js +131 -0
  48. package/build/esm/DataCache.d.ts +116 -5
  49. package/build/esm/DataCache.js +142 -20
  50. package/build/esm/Database.d.ts +165 -4
  51. package/build/esm/Database.js +224 -51
  52. package/build/esm/DbMigratorAndSeeder.d.ts +127 -26
  53. package/build/esm/DbMigratorAndSeeder.js +184 -71
  54. package/build/esm/RedisDataLoader.d.ts +144 -21
  55. package/build/esm/RedisDataLoader.js +179 -50
  56. package/build/esm/apiContext.d.ts +0 -8
  57. package/build/esm/apiContext.js +12 -27
  58. package/build/esm/checkItHelpers.d.ts +32 -0
  59. package/build/esm/checkItHelpers.js +73 -7
  60. package/build/esm/commonValidators.d.ts +107 -16
  61. package/build/esm/commonValidators.js +209 -105
  62. package/build/esm/configBuilder.d.ts +23 -0
  63. package/build/esm/configBuilder.js +69 -0
  64. package/build/esm/constants.d.ts +134 -17
  65. package/build/esm/constants.js +94 -14
  66. package/build/esm/dbHelpers.d.ts +89 -29
  67. package/build/esm/dbHelpers.js +171 -81
  68. package/build/esm/dbSeeder.d.ts +10 -1
  69. package/build/esm/dbSeeder.js +81 -16
  70. package/build/esm/dbTableHelpers.d.ts +122 -5
  71. package/build/esm/dbTableHelpers.js +152 -14
  72. package/build/esm/downloadHelpers.d.ts +24 -1
  73. package/build/esm/downloadHelpers.js +51 -21
  74. package/build/esm/index.d.ts +5 -2
  75. package/build/esm/index.js +5 -2
  76. package/build/esm/interfaces/ApiContext.d.ts +7 -3
  77. package/build/esm/interfaces/ApiContextInterface.d.ts +1 -1
  78. package/build/esm/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  79. package/build/esm/interfaces/BaseControllerPropsInterface.js +1 -0
  80. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  81. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  82. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +87 -9
  83. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  84. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  85. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.js +2 -0
  86. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  87. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  88. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  89. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.js +2 -0
  90. package/build/esm/interfaces/BuildConfigOptions.d.ts +18 -0
  91. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  92. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  93. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  94. package/build/esm/interfaces/CacheInterface.d.ts +18 -1
  95. package/build/esm/interfaces/CacheInterface.js +1 -0
  96. package/build/esm/interfaces/CoreActionInterface.d.ts +20 -0
  97. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +38 -4
  98. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  99. package/build/esm/interfaces/DataCachePropsInterface.d.ts +21 -0
  100. package/build/esm/interfaces/DataCachePropsInterface.js +2 -0
  101. package/build/esm/interfaces/DatabaseOptions.d.ts +24 -10
  102. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  103. package/build/esm/interfaces/DatabaseReadInterface.d.ts +58 -3
  104. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  105. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  106. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  107. package/build/esm/interfaces/DownloadFileArgs.d.ts +21 -2
  108. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  109. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  110. package/build/esm/interfaces/ListArgsInterface.d.ts +18 -0
  111. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  112. package/build/esm/interfaces/LoaderInterface.d.ts +36 -1
  113. package/build/esm/interfaces/LoaderInterface.js +1 -0
  114. package/build/esm/interfaces/UserTokenParams.d.ts +23 -5
  115. package/build/esm/interfaces/UserTokenParams.js +1 -0
  116. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  117. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  118. package/build/esm/interfaces/index.d.ts +4 -0
  119. package/build/esm/interfaces/index.js +4 -0
  120. package/build/esm/knexConfigBuilder.d.ts +25 -0
  121. package/build/esm/knexConfigBuilder.js +100 -36
  122. package/build/esm/parseIds.d.ts +6 -0
  123. package/build/esm/parseIds.js +13 -0
  124. package/build/esm/passwordHelpers.d.ts +22 -0
  125. package/build/esm/passwordHelpers.js +40 -8
  126. package/build/esm/redisClient.d.ts +57 -4
  127. package/build/esm/redisClient.js +40 -54
  128. package/build/esm/resolveClientIp.d.ts +15 -0
  129. package/build/esm/resolveClientIp.js +34 -0
  130. package/build/esm/resolversHelpers.d.ts +21 -1
  131. package/build/esm/resolversHelpers.js +48 -26
  132. package/build/esm/userToken.d.ts +50 -1
  133. package/build/esm/userToken.js +85 -20
  134. package/build/esm/utils.d.ts +20 -2
  135. package/build/esm/utils.js +23 -13
  136. package/build/index.d.ts +5 -2
  137. package/build/index.js +5 -2
  138. package/build/interfaces/ApiContext.d.ts +7 -3
  139. package/build/interfaces/ApiContextInterface.d.ts +1 -1
  140. package/build/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  141. package/build/interfaces/BaseControllerPropsInterface.js +2 -0
  142. package/build/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  143. package/build/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  144. package/build/interfaces/BaseCorePropsInterface.d.ts +87 -9
  145. package/build/interfaces/BaseCorePropsInterface.js +1 -0
  146. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  147. package/build/interfaces/BaseExternalApiGatewayPropsInterface.js +3 -0
  148. package/build/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  149. package/build/interfaces/BaseGatewayPropsInterface.js +1 -0
  150. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  151. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.js +3 -0
  152. package/build/interfaces/BuildConfigOptions.d.ts +18 -0
  153. package/build/interfaces/BuildConfigOptions.js +1 -0
  154. package/build/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  155. package/build/interfaces/BuildListQueryArgsInterface.js +1 -0
  156. package/build/interfaces/CacheInterface.d.ts +18 -1
  157. package/build/interfaces/CacheInterface.js +1 -0
  158. package/build/interfaces/CoreActionInterface.d.ts +20 -0
  159. package/build/interfaces/CreateUserTokenArgs.d.ts +38 -4
  160. package/build/interfaces/CreateUserTokenArgs.js +1 -0
  161. package/build/interfaces/DataCachePropsInterface.d.ts +21 -0
  162. package/build/interfaces/DataCachePropsInterface.js +3 -0
  163. package/build/interfaces/DatabaseOptions.d.ts +24 -10
  164. package/build/interfaces/DatabaseOptions.js +1 -0
  165. package/build/interfaces/DatabaseReadInterface.d.ts +58 -3
  166. package/build/interfaces/DatabaseReadInterface.js +1 -0
  167. package/build/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  168. package/build/interfaces/DbFieldAddDefaultInterface.js +1 -0
  169. package/build/interfaces/DownloadFileArgs.d.ts +21 -2
  170. package/build/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  171. package/build/interfaces/ExtractCredentialsArgs.js +1 -0
  172. package/build/interfaces/ListArgsInterface.d.ts +18 -0
  173. package/build/interfaces/ListArgsInterface.js +1 -0
  174. package/build/interfaces/LoaderInterface.d.ts +36 -1
  175. package/build/interfaces/LoaderInterface.js +1 -0
  176. package/build/interfaces/UserTokenParams.d.ts +23 -5
  177. package/build/interfaces/UserTokenParams.js +1 -0
  178. package/build/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  179. package/build/interfaces/VerifyUserTokenArgs.js +1 -0
  180. package/build/interfaces/index.d.ts +4 -0
  181. package/build/interfaces/index.js +4 -0
  182. package/build/knexConfigBuilder.d.ts +25 -0
  183. package/build/knexConfigBuilder.js +99 -35
  184. package/build/parseIds.d.ts +6 -0
  185. package/build/parseIds.js +17 -0
  186. package/build/passwordHelpers.d.ts +22 -0
  187. package/build/passwordHelpers.js +40 -8
  188. package/build/redisClient.d.ts +57 -4
  189. package/build/redisClient.js +40 -54
  190. package/build/resolveClientIp.d.ts +15 -0
  191. package/build/resolveClientIp.js +38 -0
  192. package/build/resolversHelpers.d.ts +21 -1
  193. package/build/resolversHelpers.js +48 -26
  194. package/build/userToken.d.ts +50 -1
  195. package/build/userToken.js +85 -20
  196. package/build/utils.d.ts +20 -2
  197. package/build/utils.js +24 -16
  198. package/package.json +19 -18
  199. package/build/baseController.d.ts +0 -17
  200. package/build/baseController.js +0 -64
  201. package/build/configBulder.d.ts +0 -2
  202. package/build/configBulder.js +0 -36
  203. package/build/esm/baseController.d.ts +0 -17
  204. package/build/esm/baseController.js +0 -58
  205. package/build/esm/configBulder.d.ts +0 -2
  206. package/build/esm/configBulder.js +0 -32
package/README.md CHANGED
@@ -1,178 +1,1454 @@
1
- # Backend Helpers
2
-
3
- This library has a variety of classes and functions to simplify building backend applications with the specific architecture within `@sdflc` ecosystem.
4
-
5
- ## Classes
1
+ # @sdflc/backend-helpers
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.
4
+
5
+ ---
6
+
7
+ ## Table of contents
8
+
9
+ - [Installation](#installation)
10
+ - [Requirements](#requirements)
11
+ - [Architecture overview](#architecture-overview)
12
+ - [Quick start](#quick-start)
13
+ - [Configuration](#configuration)
14
+ - [buildConfig](#buildconfig)
15
+ - [buildKnexConfig](#buildknexconfig)
16
+ - [Application setup](#application-setup)
17
+ - [Logger](#logger)
18
+ - [Redis client](#redis-client)
19
+ - [Knex handle](#knex-handle)
20
+ - [Context](#context)
21
+ - [Express app](#express-app)
22
+ - [Core concepts](#core-concepts)
23
+ - [ApiContext](#apicontext)
24
+ - [BaseCore](#basecore)
25
+ - [BaseGateway](#basegateway)
26
+ - [BaseController](#basecontroller)
27
+ - [BaseRestApiCrudController](#baserestapicrudcontroller)
28
+ - [BaseExternalApiGateway](#baseexternalapigatewayx)
29
+ - [Database](#database)
30
+ - [Database class](#database-class)
31
+ - [DataCache and custom loaders](#datacache-and-custom-loaders)
32
+ - [RedisDataLoader](#redisdataloader)
33
+ - [Authentication](#authentication)
34
+ - [JWT token helpers](#jwt-token-helpers)
35
+ - [GraphQL helpers](#graphql-helpers)
36
+ - [buildDefaultResolvers](#builddefaultresolvers)
37
+ - [CLI utilities](#cli-utilities)
38
+ - [Migration and seeding utilities](#migration-and-seeding-utilities)
39
+ - [DbMigratorAndSeeder](#dbmigratorandseeder)
40
+ - [dbHelpers](#dbhelpers)
41
+ - [Field helpers](#field-helpers)
42
+ - [Validation helpers](#validation-helpers)
43
+ - [Utility functions](#utility-functions)
44
+ - [downloadFile](#downloadfile)
45
+ - [passwordHelpers](#passwordhelpers)
46
+ - [Constants](#constants)
47
+ - [Interfaces reference](#interfaces-reference)
48
+
49
+ ---
50
+
51
+ ## Installation
52
+
53
+ ```bash
54
+ npm install @sdflc/backend-helpers
55
+ ```
56
+
57
+ ---
58
+
59
+ ## Requirements
60
+
61
+ - Node.js >= 22
62
+ - TypeScript >= 5.7
63
+ - PostgreSQL or MSSQL (via Knex)
64
+
65
+ ---
66
+
67
+ ## Architecture overview
68
+
69
+ The library implements a simplified variation of **Clean Architecture** — a layered approach where each layer has a single, well-defined responsibility and dependencies only flow inward.
70
+
71
+ ```
72
+ Application layer → GraphQL resolvers / REST controllers / CLI
73
+ Accept requests from the outside world and optionally
74
+ transform inputs before passing them to cores.
75
+
76
+ Business layer → Core classes (BaseCore subclasses)
77
+ Manage transactions, handle request-level authentication
78
+ and validation, enforce business rules, normalise
79
+ responses into a consistent OpResult shape.
80
+
81
+ Data layer → Gateway classes (BaseGateway subclasses)
82
+ Perform CRUD operations on database tables, run complex
83
+ queries with joins and filters, communicate with
84
+ external APIs and third-party services.
85
+ ```
86
+
87
+ Each inbound request — whether from an HTTP client, a GraphQL operation, or a CLI command — creates a fresh **ApiContext** that carries the database connection, all gateway instances, all core instances, and request-scoped data (userId, spaceId, headers, etc.).
88
+
89
+ **Key invariants:**
90
+
91
+ - Gateways and cores are instantiated **per-request** and must never be reused across requests
92
+ - The data layer (gateways) has no knowledge of HTTP, GraphQL, or authentication — it only handles data
93
+ - The business layer (cores) has no knowledge of transport details — it receives plain args and returns OpResults
94
+ - The application layer (controllers/resolvers/CLI) has no direct database access — it goes through cores
95
+
96
+ This separation means the same core logic is accessible identically from a GraphQL resolver, a REST endpoint, and a CLI command — as demonstrated throughout this documentation.
97
+
98
+ ---
99
+
100
+ ## Quick start
101
+
102
+ The typical project structure:
103
+
104
+ ```
105
+ src/
106
+ config.ts ← environment config via buildConfig()
107
+ knexConfig.ts ← Knex config via buildKnexConfig()
108
+ knexHandle.ts ← Knex instance for migrations/seeds/CLI
109
+ logger.ts ← shared logger instance
110
+ redisClient.ts ← optional Redis client
111
+ context.ts ← per-request ApiContext factory
112
+ app.ts ← Express + Apollo setup
113
+ index.ts ← server entry point
114
+ core/
115
+ AppCore.ts ← project-level base core
116
+ NoteCore.ts ← resource-specific core
117
+ gateways/
118
+ NoteGw.ts ← resource-specific gateway
119
+ app/
120
+ graphql/
121
+ types/ ← GraphQL type definitions
122
+ resolvers/ ← GraphQL resolvers
123
+ restapi/ ← REST controllers
124
+ cli/
125
+ index.ts ← CLI entry point
126
+ ```
127
+
128
+ ---
129
+
130
+ ## Configuration
131
+
132
+ ### buildConfig
133
+
134
+ Loads environment variables from a `.env` file and returns a flat camelCase config object. Boolean strings (`'true'`/`'1'` → `true`, `'false'`/`'0'` → `false`) are coerced automatically.
135
+
136
+ ```typescript
137
+ // src/config.ts
138
+ import { buildConfig } from '@sdflc/backend-helpers';
139
+
140
+ const config = buildConfig(__dirname, {
141
+ envFile: '../.env',
142
+ envFileExample: '../.env.example',
143
+ defaultNodeEnv: 'development',
144
+ allowEmptyValues: true,
145
+ });
146
+
147
+ export default {
148
+ ...config,
149
+ // Post-process any values that need further transformation:
150
+ currencies: (config.allowedCurrencies || '').split(','),
151
+ };
152
+ ```
153
+
154
+ ```bash
155
+ # .env.example — documents all required variables
156
+ NODE_ENV=development
157
+ DB_TYPE=pg
158
+ DB_HOST=localhost
159
+ DB_PORT=5432
160
+ DB_NAME=myapp
161
+ DB_SCHEMA=public
162
+ DB_USER=postgres
163
+ DB_PASSWORD=secret
164
+ DB_POOL_MIN=0
165
+ DB_POOL_MAX=10
166
+ JWT_SECRET=change-me
167
+ LOG_LEVEL=debug
168
+ REDIS_HOST=
169
+ REDIS_PORT=6379
170
+ REDIS_PASSWORD=
171
+ REDIS_SSL=false
172
+ CACHE_TTL=300
173
+ COOKIE_NAME=token
174
+ FINGERPRINT_COOKIE_NAME=fp
175
+ INTERSERVICE_API_KEY=
176
+ ```
177
+
178
+ ---
179
+
180
+ ### buildKnexConfig
181
+
182
+ Builds a Knex configuration object for the current environment. The library handles port coercion, MSSQL connection options, and PostgreSQL `searchPath` automatically — no manual post-processing needed.
183
+
184
+ ```typescript
185
+ // src/knexConfig.ts
186
+ import { buildKnexConfig } from '@sdflc/backend-helpers';
187
+ import config from './config';
188
+
189
+ const knexConfig = buildKnexConfig(__dirname, {
190
+ ...config,
191
+ migrationsFolder: 'database/migrations',
192
+ seedsFolder: 'database/seeds',
193
+ migrationsTemplateFileName: 'migrations-template.ts',
194
+ useSchemaForMigrationsTable: true,
195
+ });
196
+
197
+ export default knexConfig;
198
+ ```
199
+
200
+ Built-in behaviours:
201
+
202
+ - All query results are post-processed to camelCase
203
+ - All identifiers are converted to snake_case
204
+ - Database port is coerced to `Number`
205
+ - `connectionTimeout: 30000` is set by default
206
+ - MSSQL `connection.options` added automatically when `dbType === 'mssql'`
207
+ - PostgreSQL `searchPath` set automatically when `dbType === 'pg'` and `dbSchema` is provided
208
+ - `debug` is forced to `false` in production
209
+
210
+ #### Available options
211
+
212
+ | Option | Type | Description |
213
+ | --------------------------------------- | --------- | ------------------------------------------------------- |
214
+ | `dbType` | `string` | `'pg'` or `'mssql'` (default: `'pg'`) |
215
+ | `dbHost/Port/Name/Schema/User/Password` | `string` | Connection parameters |
216
+ | `dbPoolMin/Max` | `number` | Pool size (defaults: `0`/`50`) |
217
+ | `dbPool` | `object` | Full tarn pool config (overrides min/max) |
218
+ | `migrationsFolder` | `string` | Path to migrations directory |
219
+ | `seedsFolder` | `string` | Seeds directory (all environments) |
220
+ | `seedsFolderDev/Prod` | `string` | Environment-specific seeds directories |
221
+ | `migrationsTable` | `string` | Migrations tracking table name |
222
+ | `migrationsTemplateFileName` | `string` | Template for `knex migrate:make` |
223
+ | `useSchemaForMigrationsTable` | `boolean` | Scope migrations table to schema |
224
+ | `wrapIdentifierOverrideMap` | `object` | Override snake_case conversion for specific identifiers |
225
+
226
+ ---
227
+
228
+ ## Application setup
229
+
230
+ ### Logger
231
+
232
+ ```typescript
233
+ // src/logger.ts
234
+ import { Logger } from '@sdflc/utils';
235
+ import config from './config';
236
+
237
+ export const logger = new Logger({ level: config.logLevel });
238
+ ```
239
+
240
+ ---
241
+
242
+ ### Redis client
243
+
244
+ ```typescript
245
+ // src/redisClient.ts
246
+ import { createRedisClient } from '@sdflc/backend-helpers';
247
+ import config from './config';
248
+ import { logger } from './logger';
249
+
250
+ // Returns null if redisHost is not configured — safe to pass to DataCache
251
+ export const redisClient = config.redisHost
252
+ ? createRedisClient({
253
+ redisHost: config.redisHost,
254
+ redisPort: config.redisPort,
255
+ redisPassword: config.redisPassword,
256
+ redisSsl: config.redisSsl,
257
+ connectionTimeout: 5000,
258
+ pingInterval: 5000,
259
+ onConnecting: () => logger.log('Redis connecting'),
260
+ onConnected: () => logger.log('Redis connected'),
261
+ onDisconnected: () => logger.log('Redis disconnected'),
262
+ onReconnecting: () => logger.log('Redis reconnecting'),
263
+ onError: (err) => logger.error('Redis error:', err),
264
+ })
265
+ : null;
266
+
267
+ // Call redisClient.connect() at startup — see app.ts and cli/index.ts
268
+ ```
269
+
270
+ > 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
+
272
+ ---
273
+
274
+ ### Knex handle
275
+
276
+ Used directly for migrations and seeds (separate from the per-request `Database` instance).
277
+
278
+ ```typescript
279
+ // src/knexHandle.ts
280
+ import knex from 'knex';
281
+ import knexConfig from './knexConfig';
282
+
283
+ export default knex({
284
+ ...knexConfig,
285
+ pool: {
286
+ min: 2,
287
+ max: 20,
288
+ acquireTimeoutMillis: 30000,
289
+ createTimeoutMillis: 30000,
290
+ destroyTimeoutMillis: 5000,
291
+ idleTimeoutMillis: 30000,
292
+ reapIntervalMillis: 1000,
293
+ createRetryIntervalMillis: 200,
294
+ },
295
+ acquireConnectionTimeout: 30000,
296
+ });
297
+ ```
298
+
299
+ ---
300
+
301
+ ### Context
302
+
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 — this is the single source of truth for how cores and gateways are wired together.
304
+
305
+ ```typescript
306
+ // src/context.ts
307
+ import { createContextDefault } from '@sdflc/backend-helpers';
308
+ import { STATUSES } from '@sdflc/utils';
309
+ import dayjs from 'dayjs';
310
+
311
+ import config from './config';
312
+ import * as cores from './core';
313
+ import * as gateways from './gateways';
314
+ import knexConfig from './knexConfig';
315
+ import { redisClient } from './redisClient';
316
+ import { logger } from './logger';
317
+
318
+ export const createContext = async (args: any) => {
319
+ return createContextDefault({
320
+ req: args.req,
321
+ dbSchema: config.dbSchema,
322
+ cores,
323
+ gateways,
324
+ knexConfig,
325
+ isProduction: config.isProduction,
326
+ logger,
327
+ doAuth: true,
328
+ interserviceApiKey: config.interserviceApiKey,
329
+ jwtSecret: config.jwtSecret,
330
+ verifyTokenArgs: {
331
+ ignoreExpiration: false,
332
+ ignoreNotBefore: false,
333
+ },
334
+ // Provide extra props to every gateway constructor
335
+ getGatewayContext: () => ({
336
+ redisClient,
337
+ cacheTtl: config.cacheTtl,
338
+ activeStatuses: [STATUSES.ACTIVE],
339
+ }),
340
+ // Extend context with app-specific fields after construction
341
+ extendContext: ({ context }: any) => {
342
+ context.nowUtc = dayjs().utc().toDate();
343
+ context.space = {
344
+ cookieName: config.cookieName,
345
+ fingerprintCookieName: config.fingerprintCookieName,
346
+ };
347
+ },
348
+ });
349
+ };
350
+ ```
351
+
352
+ ---
353
+
354
+ ### Express app
355
+
356
+ ```typescript
357
+ // src/app.ts
358
+ import express from 'express';
359
+ import cors from 'cors';
360
+ import cookieParser from 'cookie-parser';
361
+ import http from 'http';
362
+ import dayjs from 'dayjs';
363
+ import { ApolloServer } from '@apollo/server';
364
+ import { expressMiddleware } from '@as-integrations/express5';
365
+ import { buildSubgraphSchema } from '@apollo/subgraph';
366
+ import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
367
+ import {
368
+ ApolloServerPluginUsageReportingDisabled,
369
+ ApolloServerPluginInlineTraceDisabled,
370
+ } from '@apollo/server/plugin/disabled';
371
+ import { OpResult, OP_RESULT_CODES } from '@sdflc/api-helpers';
372
+ import { HEADERS } from '@sdflc/backend-helpers';
373
+
374
+ import typeDefs from './app/graphql/types';
375
+ import resolvers from './app/graphql/resolvers';
376
+ import { createContext } from './context';
377
+ import config from './config';
378
+ import * as controllers from './app/restapi';
379
+ import { redisClient } from './redisClient';
380
+ import { isOpResult } from './utils';
381
+ import packageJson from '../package.json';
382
+
383
+ const corsOptions = {
384
+ origin: (_origin: any, callback: any) => callback(null, true),
385
+ credentials: true,
386
+ };
387
+
388
+ const configureApp = async (app: any) => {
389
+ app.disable('x-powered-by');
390
+
391
+ app.use('/api/webhooks/stripe', express.raw({ type: 'application/json' }));
392
+ app.use(express.json({ limit: config.maxReqBodySize }));
393
+ app.use(express.urlencoded({ limit: config.maxReqBodySize, extended: true }));
394
+ app.use(cookieParser());
395
+ app.use(cors(corsOptions));
396
+
397
+ // Health check
398
+ app.get('/', (req: any, res: any) => {
399
+ res.json(
400
+ new OpResult({
401
+ data: {
402
+ version: packageJson.version,
403
+ name: packageJson.name,
404
+ utcDateTime: dayjs().toISOString(),
405
+ remoteIp: req.headers[HEADERS.IP_ADDRESS] || req.socket?.remoteAddress,
406
+ },
407
+ }).toJS(),
408
+ );
409
+ });
410
+
411
+ // Attach context to non-GraphQL requests
412
+ app.use(async (req: any, _res: any, next: any) => {
413
+ if (req.path !== '/graphql') {
414
+ req.context = await createContext({ req });
415
+ }
416
+ next();
417
+ });
418
+
419
+ // Register REST controllers
420
+ Object.keys(controllers).forEach((key) => {
421
+ const controller = new (controllers as any)[key]();
422
+ controller.init({ app });
423
+ });
424
+
425
+ const httpServer = http.createServer(app);
426
+
427
+ const apolloServer = new ApolloServer({
428
+ schema: buildSubgraphSchema([{ typeDefs, resolvers: resolvers as any }]),
429
+ introspection: !config.isProduction,
430
+ plugins: [
431
+ ApolloServerPluginDrainHttpServer({ httpServer }),
432
+ ApolloServerPluginUsageReportingDisabled(),
433
+ ApolloServerPluginInlineTraceDisabled(),
434
+ ],
435
+ });
436
+
437
+ if (redisClient) {
438
+ await redisClient.connect();
439
+ }
440
+
441
+ await apolloServer.start();
442
+
443
+ app.use(
444
+ config.graphqlUrl,
445
+ cors(corsOptions),
446
+ express.json(),
447
+ expressMiddleware(apolloServer, { context: createContext }),
448
+ );
449
+
450
+ // 404 handler
451
+ app.use((req: any, res: any) => {
452
+ res
453
+ .status(404)
454
+ .json(
455
+ new OpResult()
456
+ .addError('', `API entry point not supported: '${req.originalUrl}'`, OP_RESULT_CODES.EXCEPTION)
457
+ .toJS(),
458
+ );
459
+ });
460
+
461
+ // Global error handler
462
+ app.use((err: any, _req: any, res: any, _next: any) => {
463
+ if (isOpResult(err)) {
464
+ res.status(500).json(err.toJS());
465
+ } else if (typeof err === 'string') {
466
+ res.status(500).json(new OpResult().addError('', err, OP_RESULT_CODES.FAILED).toJS());
467
+ } else if (err instanceof Error) {
468
+ res.status(500).json(new OpResult().addError('', err.message, OP_RESULT_CODES.FAILED).toJS());
469
+ } else {
470
+ res
471
+ .status(500)
472
+ .json(
473
+ new OpResult()
474
+ .setData(err)
475
+ .addError('', 'An error has occurred when processing this request', OP_RESULT_CODES.FAILED)
476
+ .toJS(),
477
+ );
478
+ }
479
+ });
480
+
481
+ return httpServer;
482
+ };
483
+
484
+ export default configureApp;
485
+ ```
486
+
487
+ ---
488
+
489
+ ## Core concepts
490
+
491
+ ### ApiContext
492
+
493
+ The request context object shared across all layers. Created once per request — or once per CLI invocation.
494
+
495
+ | Field | Type | Description |
496
+ | ------------- | --------------------- | ------------------------------------------------- |
497
+ | `requestId` | `string` | UUID generated per request |
498
+ | `cores` | `Record<string, any>` | All registered core instances (camelCase keys) |
499
+ | `gateways` | `Record<string, any>` | All registered gateway instances (camelCase keys) |
500
+ | `db` | `Database` | Shared database instance |
501
+ | `userId` | `string?` | Populated after successful authentication |
502
+ | `accountId` | `string?` | Populated after successful authentication |
503
+ | `roleId` | `string?` | Populated after successful authentication |
504
+ | `spaceId` | `string?` | From request headers or JWT token |
505
+ | `lang` | `string?` | Resolved language for the request |
506
+ | `req` / `res` | `any` | Express request/response objects |
507
+
508
+ ---
6
509
 
7
510
  ### BaseCore
8
511
 
9
- This is the class that should be extended when you create a new core class. This is where all the business logic should be happeninng when processing request.
10
-
11
- #### Constructor
12
-
13
- Here are the props to be passed to the BaseCore constructor:
14
-
15
- - db: Database - an object of Database class
16
- - context?: any - the request context where you can add all you need, optional
17
- - gateway?: any - main gateway class object that will be working with DB or 3rd part API
18
- - gateways?: any - an object
19
- - isProduction: boolean - true when the app is in production
20
- - logLevel: LoggerLevels - log leves: 0 - none, 1 - errors, 2 - warnings, 3 - messages, 4 - all
21
- - logger?: Logger - object of Logger class to be used as logger
22
- - name?: string - name of the core
23
- - requestId: string - Unique ID of a request processed, can be used for troubleshooting
24
- - doAuth: boolean - call authorize method or not an incoming request
25
- - doingWhat?: BaseCoreDoingWhatInterface - an object with text descriptions of each action, used to generate generic error message sent to user on an exception
26
- - validators?: BaseCoreValidatorsInterface - an object with validator functions to be used to validate incoming data
27
- - spaceGw?: BaseGateway - gateway to find a space, i.e. configration of the app. Each app can have several configurations to be used as one instance for different applications
28
- - interserviceApiKey?: string - API key to be used to authenticate incoming request from another microservice, optional
29
- - jwtSecret?: string - secret to be used to validate Authorize Bearer token on incoming request, optional
30
- - verifytokenArgs?: VerifyUserTokenArgs - optional parameters for JWT token validation, like algorithm, etc
31
-
32
- #### getDb()
33
-
34
- #### getRequestId()
35
-
36
- #### getContext(key?: string)
37
-
38
- #### getGateways()
39
-
40
- #### success(data: any, code?: number): any
41
-
42
- #### failure(code: number, errorMsg: string, data?: any)
43
-
44
- #### validationFailure(ex: any): any
45
-
46
- #### exceptionFailure(ex: any, doingWhat: string | any, data?: any)
47
-
48
- #### checkResult(args: any)
49
-
50
- #### runAction(opt: CoreActionInterface)
51
-
52
- #### Default Actions
53
-
54
- ##### list(args: any)
55
-
56
- ##### get(args: any)
57
-
58
- ##### getMany(args: any)
59
-
60
- ##### create(args: any)
61
-
62
- ##### createMany(args: any)
63
-
64
- ##### update(args: any)
65
-
66
- ##### updateMany(args: any)
67
-
68
- ##### set(args: any)
69
-
70
- ##### remove(args: any)
71
-
72
- ##### removeMany(args: any)
73
-
74
- #### Default Action related events
75
-
76
- ##### beforeList(params: any, opt?: BaseCoreActionsInterface): Promise<any>
77
-
78
- ##### afterList(params: any, opt?: BaseCoreActionsInterface): Promise<any>
79
-
80
- ##### beforeCreate(params: any, opt?: BaseCoreActionsInterface): Promise<any>
81
-
82
- ##### afterCreate(params: any, opt?: BaseCoreActionsInterface): Promise<any>
83
-
84
- ##### beforeCreateMany(params: any, opt?: BaseCoreActionsInterface): Promise<any>
85
-
86
- ##### afterCreateMany(params: any, opt?: BaseCoreActionsInterface): Promise<any>
87
-
88
- ##### beforeUpdate(params: any, opt?: BaseCoreActionsInterface): Promise<any>
89
-
90
- ##### afterUpdate(params: any, opt?: BaseCoreActionsInterface): Promise<any>
91
-
92
- ##### beforeUpdateMany(params: any, opt?: BaseCoreActionsInterface): Promise<any>
93
-
94
- #### afterUpdateMany(params: any, opt?: BaseCoreActionsInterface): Promise<any>
95
-
96
- ##### beforeSet(params: any, opt?: BaseCoreActionsInterface): Promise<any>
97
-
98
- ##### afterSet(params: any, opt?: BaseCoreActionsInterface): Promise<any>
99
-
100
- ##### beforeRemove(params: any, opt?: BaseCoreActionsInterface): Promise<any>
101
-
102
- ##### afterRemove(params: any, opt?: BaseCoreActionsInterface): Promise<any>
103
-
104
- ##### beforeRemoveMany(params: any, opt?: BaseCoreActionsInterface): Promise<any>
105
-
106
- ##### afterRemoveMany(params: any, opt?: BaseCoreActionsInterface): Promise<any>
107
-
108
- ##### onException(params: any, opt?: BaseCoreActionsInterface): Promise<any>
109
-
110
- #### Authorization
111
-
112
- #### authenticate(params: any, opt?: BaseCoreActionsInterface)
512
+ The base class for all business logic. The `AppCore` pattern lets you add project-wide helpers once and extend it for every resource.
513
+
514
+ ```typescript
515
+ // src/core/AppCore.ts
516
+ import { BaseCore, BaseCorePropsInterface } from '@sdflc/backend-helpers';
517
+
518
+ class AppCore extends BaseCore {
519
+ constructor(props: BaseCorePropsInterface) {
520
+ super(props);
521
+ }
522
+
523
+ // Add project-wide helpers available to all core subclasses
524
+ public now(): Date {
525
+ return new Date();
526
+ }
527
+ }
528
+
529
+ export { AppCore };
530
+ ```
531
+
532
+ ```typescript
533
+ // src/core/NoteCore.ts
534
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
535
+ import { BaseCorePropsInterface, BaseCoreActionsInterface, BaseCoreValidatorsInterface } from '@sdflc/backend-helpers';
536
+
537
+ import { AppCore } from './AppCore';
538
+ import { validators } from './validators/noteValidators';
539
+
540
+ class NoteCore extends AppCore {
541
+ constructor(props: BaseCorePropsInterface) {
542
+ super({
543
+ ...props,
544
+ gatewayName: 'noteGw',
545
+ name: 'Note',
546
+ doAuth: true,
547
+ doingWhat: {
548
+ list: 'listing notes',
549
+ get: 'getting a note',
550
+ getMany: 'getting multiple notes',
551
+ create: 'creating a note',
552
+ update: 'updating a note',
553
+ remove: 'removing a note',
554
+ removeMany: 'removing multiple notes',
555
+ },
556
+ });
557
+ }
558
+
559
+ public getValidators(): BaseCoreValidatorsInterface {
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
+ }
610
+ }
611
+
612
+ export { NoteCore };
613
+ ```
614
+
615
+ #### Per-action authentication
616
+
617
+ ```typescript
618
+ // Require auth globally but allow public listing:
619
+ new NoteCore({
620
+ doAuth: true,
621
+ doAuthOnAction: { list: false },
622
+ ...props,
623
+ });
624
+ ```
625
+
626
+ #### Soft authentication (`tryAuth`)
627
+
628
+ For public endpoints that behave differently when a user is authenticated (e.g. show "saved" state):
629
+
630
+ ```typescript
631
+ return this.runAction({
632
+ args,
633
+ tryAuth: true, // populate context if token present, never fail
634
+ hasTransaction: false,
635
+ doingWhat: 'listing public notes',
636
+ action: async (args, opt) => {
637
+ const isAuthenticated = !!this.getContext().userId;
638
+ // proceed with or without an authenticated user
639
+ },
640
+ });
641
+ ```
642
+
643
+ #### Before/after hooks
644
+
645
+ | Hook | Called by | Purpose |
646
+ | ------------------ | ------------------------- | ---------------------------------------------- |
647
+ | `beforeList` | `list()` | Transform/scope filter args |
648
+ | `afterList` | `list()` | Transform result array |
649
+ | `beforeGet` | `get()` | Validate/transform id args |
650
+ | `afterGet` | `get()` | Enforce ownership, transform single result |
651
+ | `beforeGetMany` | `getMany()` | Transform ids args |
652
+ | `afterGetMany` | `getMany()` | Filter/transform multiple results |
653
+ | `beforeCreate` | `create()` | Enrich params (inject userId, accountId, etc.) |
654
+ | `afterCreate` | `create()` | Transform created records |
655
+ | `beforeUpdate` | `update()` | Transform params, inject ownership into where |
656
+ | `afterUpdate` | `update()` | Transform updated records, send notifications |
657
+ | `beforeRemove` | `remove()` | Inject ownership into where clause |
658
+ | `afterRemove` | `remove()` | Post-removal side effects |
659
+ | `beforeRemoveMany` | `removeMany()` | Inject ownership into each where clause |
660
+ | `afterRemoveMany` | `removeMany()` | Post-removal side effects |
661
+ | `processItemOnIn` | All before-mutation hooks | Normalise inbound data |
662
+ | `processItemOnOut` | All after hooks | Shape outbound data |
663
+
664
+ ---
113
665
 
114
666
  ### BaseGateway
115
667
 
116
- This is the class that should be extended when you create a new gateway class. This is where your code works with database or 3rd party API or do some works of the lowest level. Gateways are used by the core classes to actually do the job to implement one or another business logic.
117
-
118
- #### constructor(props: BaseGatewayInterface)
668
+ The base class for all database-backed data access. One gateway per table.
669
+
670
+ ```typescript
671
+ // src/gateways/NoteGw.ts
672
+ import { BaseGateway, BaseGatewayPropsInterface } from '@sdflc/backend-helpers';
673
+
674
+ class NoteGw extends BaseGateway {
675
+ constructor(props: BaseGatewayPropsInterface) {
676
+ super({
677
+ ...props,
678
+ table: 'note',
679
+ keyPrefix: 'note',
680
+ hasStatus: true,
681
+ hasCreatedAt: true,
682
+ hasUpdatedAt: true,
683
+ hasRemovedAt: true, // soft-delete
684
+ hasCreatedBy: true,
685
+ hasUpdatedBy: true,
686
+ hasUserId: true,
687
+ selectFields: ['note.*'],
688
+ idField: 'note.id',
689
+ idFieldUpdateRemove: 'id',
690
+ defaultSorting: [{ name: 'created_at', order: 'desc' }],
691
+ });
692
+ }
693
+
694
+ async onListFilter(query: any, filterParams: any): Promise<void> {
695
+ await super.onListFilter(query, filterParams);
696
+
697
+ const { userId, title } = filterParams || {};
698
+
699
+ if (userId) {
700
+ query.where('note.user_id', userId);
701
+ }
702
+
703
+ if (title) {
704
+ query.whereILike('note.title', `%${title}%`);
705
+ }
706
+ }
707
+
708
+ async onUpdateFilter(query: any, whereParams: any): Promise<number> {
709
+ let count = await super.onUpdateFilter(query, whereParams);
710
+
711
+ if (whereParams?.userId != null) {
712
+ count++;
713
+ query.where({ user_id: whereParams.userId });
714
+ }
715
+
716
+ return count;
717
+ }
718
+ }
719
+
720
+ export { NoteGw };
721
+ ```
722
+
723
+ #### Gateway config flags
724
+
725
+ | Flag | Type | Description |
726
+ | ---------------------------------- | --------------------- | ---------------------------------------------- |
727
+ | `table` | `string` | Database table name |
728
+ | `idField` | `string` | Primary key for SELECT/loader (default: `id`) |
729
+ | `idFieldUpdateRemove` | `string` | Primary key for UPDATE/DELETE WHERE |
730
+ | `hasStatus` | `boolean` | Status filtering and REMOVED guard |
731
+ | `hasCreatedAt/UpdatedAt/RemovedAt` | `boolean` | Timestamp management |
732
+ | `hasCreatedBy/UpdatedBy/RemovedBy` | `boolean` | Audit user tracking |
733
+ | `hasSpace` | `boolean` | Scopes reads/writes to `context.spaceId` |
734
+ | `hasUserId` | `boolean` | Sets `userId` from context on create |
735
+ | `hasVersion` | `boolean` | Optimistic locking via version field |
736
+ | `hasLang` | `boolean` | Language-scoped records |
737
+ | `hardRemove` | `boolean` | Hard DELETE instead of soft-delete |
738
+ | `noCache` | `boolean` | Bypass DataLoader cache |
739
+ | `returnFields` | `string[]` | Columns in RETURNING clause (default: `['*']`) |
740
+ | `defaultSorting` | `SortItemInterface[]` | Default ORDER BY when none provided |
741
+ | `filterByUserField` | `string` | Auto-scope list queries to `context.userId` |
742
+ | `selectFields` | `string[]` | Columns selected when `useCache: false` |
743
+
744
+ ---
119
745
 
120
- #### generateId(args?: any)
121
-
122
- #### onListFilter(query: any, filterParams: any)
123
-
124
- #### onUpdateFilter(query: any, filterParams: any)
125
-
126
- #### onRemoveFilter(query: any, filterParams: any)
127
-
128
- #### transformOnCreate(args: any)
746
+ ### BaseController
129
747
 
130
- #### transformOnUpdate(params: any, where?: any)
748
+ Base class for custom Express REST controllers with consistent response handling.
749
+
750
+ ```typescript
751
+ // src/app/restapi/EmbedController.ts
752
+ import { BaseController } from '@sdflc/backend-helpers';
753
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
754
+ import fs from 'fs';
755
+ import path from 'path';
756
+
757
+ class EmbedController extends BaseController {
758
+ init(props: any): void {
759
+ const { app } = props;
760
+ app.get('/api/v1/embed.js', this.getEmbedScript.bind(this));
761
+ }
762
+
763
+ async getEmbedScript(req: any, res: any): Promise<void> {
764
+ const scriptPath = path.join(__dirname, '../../public/api/v1/embed.js');
765
+
766
+ if (!fs.existsSync(scriptPath)) {
767
+ return res
768
+ .status(404)
769
+ .json(new OpResult().addError('', 'Embed script not found', OP_RESULT_CODES.NOT_FOUND).toJS());
770
+ }
771
+
772
+ const script = fs.readFileSync(scriptPath, 'utf8');
773
+ res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
774
+ res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*');
775
+ res.send(script);
776
+ }
777
+ }
778
+
779
+ export { EmbedController };
780
+ ```
781
+
782
+ The `json()` wrapper handles all response shapes automatically:
783
+
784
+ - `OpResult` → uses `result.getHttpStatus()` and `result.toJS()`
785
+ - `{ redirectUrl }` → calls `res.redirect()`
786
+ - Plain object → `200` JSON
787
+ - `null`/`undefined` → `204 No Content`
788
+
789
+ ---
790
+
791
+ ### BaseRestApiCrudController
792
+
793
+ Registers standard CRUD routes automatically. Comma-separated `:id` values route to `getMany`/`removeMany` automatically.
794
+
795
+ ```typescript
796
+ // src/app/restapi/NoteRestController.ts
797
+ import { BaseRestApiCrudController } from '@sdflc/backend-helpers';
798
+ import { createContext } from '../../context';
799
+
800
+ class NoteRestController extends BaseRestApiCrudController {
801
+ constructor() {
802
+ super({
803
+ prefix: 'note',
804
+ getContext: (req: any) => createContext({ req }),
805
+ disableCreateMany: true,
806
+ disableUpdateMany: true,
807
+ disableSet: true,
808
+ });
809
+ }
810
+ }
811
+
812
+ // In app.ts:
813
+ const controller = new NoteRestController();
814
+ controller.init({ app, root: '/api/notes' });
815
+ ```
816
+
817
+ Routes registered for `root = '/api/notes'`:
818
+
819
+ | Method | Path | Core method | Notes |
820
+ | -------- | ------------------------ | ----------------------- | --------------------------- |
821
+ | `GET` | `/api/notes` | `core.list(query)` | Query string becomes filter |
822
+ | `GET` | `/api/notes/:id` | `core.get()` | Single id |
823
+ | `GET` | `/api/notes/id1,id2,id3` | `core.getMany()` | Comma-separated ids |
824
+ | `POST` | `/api/notes` | `core.create(body)` | |
825
+ | `POST` | `/api/notes/many` | `core.createMany(body)` | Array body |
826
+ | `PUT` | `/api/notes/:id` | `core.update()` | |
827
+ | `PUT` | `/api/notes/many` | `core.updateMany()` | |
828
+ | `DELETE` | `/api/notes/:id` | `core.remove()` | Single id |
829
+ | `DELETE` | `/api/notes/id1,id2` | `core.removeMany()` | Comma-separated ids |
830
+
831
+ ---
832
+
833
+ ### BaseExternalApiGateway
834
+
835
+ Base class for external API integrations. Credentials are injected at runtime after construction.
836
+
837
+ ```typescript
838
+ // src/gateways/StripeGateway.ts
839
+ import { BaseExternalApiGateway } from '@sdflc/backend-helpers';
840
+ import Stripe from 'stripe';
841
+
842
+ interface StripeCredentials {
843
+ secretKey: string;
844
+ }
845
+
846
+ class StripeGateway extends BaseExternalApiGateway {
847
+ private client: Stripe | null = null;
848
+
849
+ protected onCredentialsSet(): void {
850
+ const { secretKey } = this.credentials as StripeCredentials;
851
+ this.client = new Stripe(secretKey);
852
+ }
853
+
854
+ async chargeCard(amount: number, currency: string): Promise<any> {
855
+ this.assertCredentials();
856
+ return this.client!.paymentIntents.create({ amount, currency });
857
+ }
858
+ }
859
+
860
+ // In a core method:
861
+ const gw = new StripeGateway({ baseUrl: 'https://api.stripe.com' });
862
+ const creds = await db.getCredentials(context.spaceId, 'stripe');
863
+ gw.setCredentials(creds); // accepts string or Record<string, any>
864
+ await gw.chargeCard(1000, 'usd');
865
+ ```
866
+
867
+ ---
868
+
869
+ ## Database
870
+
871
+ ### Database class
872
+
873
+ Wraps Knex with connection pool deduplication, transaction management, and schema support.
874
+
875
+ ```typescript
876
+ import { Database } from '@sdflc/backend-helpers';
877
+
878
+ const db = new Database({
879
+ knexConfig: { client: 'pg', connection: { host, port, user, password, database } },
880
+ dbSchema: 'public',
881
+ logger,
882
+ });
883
+
884
+ // Read utility with filtering, mapping, and computed fields:
885
+ const userMap = await db.read({
886
+ table: 'user',
887
+ selectFields: ['id', 'email', 'first_name', 'last_name'],
888
+ where: { status: 100 },
889
+ mapBy: 'id',
890
+ calculated: [{ name: 'displayName', value: (row: any) => `${row.firstName} ${row.lastName}` }],
891
+ });
892
+
893
+ // Transactions are managed automatically by BaseCore.runAction()
894
+ await db.startTransaction();
895
+ try {
896
+ await db.commitTransaction();
897
+ } catch {
898
+ await db.rollbackTransaction();
899
+ }
900
+ ```
901
+
902
+ ---
903
+
904
+ ### DataCache and custom loaders
905
+
906
+ `DataCache` is the default per-request DataLoader-backed cache. You can provide a **custom loader** when you need non-standard fetching — for example enriching records with a JOIN.
907
+
908
+ ```typescript
909
+ // src/gateways/NoteGw.ts — gateway with a custom loader
910
+ import { BaseGateway, BaseGatewayPropsInterface, DataCache } from '@sdflc/backend-helpers';
911
+
912
+ class NoteGw extends BaseGateway {
913
+ constructor(props: BaseGatewayPropsInterface) {
914
+ super({ ...props, table: 'note', keyPrefix: 'note' });
915
+
916
+ // Replace the default loader with one that enriches notes with author info
917
+ this.setLoader(
918
+ new DataCache({
919
+ ...props,
920
+ table: 'note',
921
+ idField: 'id',
922
+ keyPrefix: 'note-with-author',
923
+ loaderFn: this.batchLoadWithAuthor.bind(this),
924
+ }),
925
+ );
926
+ }
927
+
928
+ // Must return results in the same order as the input ids array
929
+ private async batchLoadWithAuthor(ids: string[]): Promise<any[]> {
930
+ const rows = await this.getDb()
931
+ .getBuilder('note')
932
+ .select('note.*', 'user.name as authorName')
933
+ .leftJoin('user', 'user.id', 'note.user_id')
934
+ .whereIn('note.id', ids);
935
+
936
+ const map = new Map(rows.map((row: any) => [row.id, row]));
937
+ return ids.map((id) => map.get(id) || null);
938
+ }
939
+ }
940
+ ```
941
+
942
+ You can also swap loaders at runtime:
943
+
944
+ ```typescript
945
+ // Swap to a Redis-backed cache:
946
+ gateway.setLoaderConfig({ redisClient, cacheTtl: 600 });
947
+
948
+ // Replace with a fully custom loader:
949
+ gateway.setLoader({
950
+ load: (id: any) => fetchFromExternalAPI(id),
951
+ loadMany: (ids: any[]) => Promise.all(ids.map(fetchFromExternalAPI)),
952
+ clear: (_key: any) => gateway,
953
+ clearAll: () => gateway,
954
+ prime: (_key: any, _value: any) => gateway,
955
+ });
956
+ ```
957
+
958
+ ---
959
+
960
+ ### RedisDataLoader
961
+
962
+ Used internally by `DataCache` when a `redisClient` is provided. Enable it for all gateways by passing `redisClient` via `getGatewayContext()`:
963
+
964
+ ```typescript
965
+ getGatewayContext: () => ({
966
+ redisClient,
967
+ cacheTtl: 300,
968
+ }),
969
+ ```
970
+
971
+ ---
972
+
973
+ ## Authentication
974
+
975
+ ### JWT token helpers
976
+
977
+ ```typescript
978
+ import { createUserToken, verifyUserToken } from '@sdflc/backend-helpers';
979
+
980
+ // Create a token with fingerprint (CSRF protection):
981
+ const result = createUserToken(
982
+ { userId: 'user-uuid', accountId: 'account-uuid', roleId: 'admin', spaceId: 'space-id', lang: 'en' },
983
+ process.env.JWT_SECRET!,
984
+ { expiresIn: '7d', useFingerprint: true },
985
+ );
986
+
987
+ if (result.didSucceed()) {
988
+ const { token, fingerprint } = result.getDataFirst();
989
+ res.cookie('fp', fingerprint, { httpOnly: true, secure: true, sameSite: 'strict' });
990
+ res.json({ token });
991
+ }
992
+
993
+ // Verify a token (called automatically by BaseCore.authenticate()):
994
+ const verifyResult = verifyUserToken(token, process.env.JWT_SECRET!, {
995
+ algorithms: ['HS256'],
996
+ audience: context.spaceId,
997
+ issuer: 'my-service',
998
+ fingerprint: req.cookies.fp,
999
+ });
1000
+
1001
+ if (verifyResult.didFail()) {
1002
+ return res.status(401).json(verifyResult.toJS());
1003
+ }
1004
+ ```
1005
+
1006
+ ---
1007
+
1008
+ ## GraphQL helpers
1009
+
1010
+ ### buildDefaultResolvers
1011
+
1012
+ Generates a standard set of GraphQL resolvers for a resource.
1013
+
1014
+ ```typescript
1015
+ // src/app/graphql/resolvers/noteResolvers.ts
1016
+ import { buildDefaultResolvers } from '@sdflc/backend-helpers';
1017
+
1018
+ const resolvers = buildDefaultResolvers({
1019
+ prefix: 'note',
1020
+ core: 'noteCore',
1021
+ disableCreateMany: true,
1022
+ disableUpdateMany: true,
1023
+ disableSet: true,
1024
+ types: {
1025
+ Note: {
1026
+ async __resolveReference(reference: any, context: any) {
1027
+ if (!reference.id) return null;
1028
+ return context.gateways.noteGw.get(reference.id);
1029
+ },
1030
+ userCreated(parent: any, _args: any, _context: any) {
1031
+ return { __typename: 'User', id: parent.createdBy };
1032
+ },
1033
+ },
1034
+ },
1035
+ });
1036
+
1037
+ export default resolvers;
1038
+ ```
1039
+
1040
+ ```typescript
1041
+ // src/app/graphql/types/noteTypes.ts
1042
+ const typeDefs = `#graphql
1043
+ type Note @key(fields: "id") {
1044
+ id: ID
1045
+ title: String
1046
+ body: String
1047
+ userId: ID
1048
+ createdAt: String
1049
+ updatedAt: String
1050
+ userCreated: User
1051
+ }
1052
+
1053
+ type NoteResult implements OpResult {
1054
+ code: Int!
1055
+ errors: [Error!]
1056
+ data: [Note!]
1057
+ }
1058
+
1059
+ input NoteInput {
1060
+ title: String!
1061
+ body: String
1062
+ }
1063
+
1064
+ input NoteFilter {
1065
+ id: [ID]
1066
+ title: String
1067
+ searchKeyword: String
1068
+ }
1069
+
1070
+ input NoteWhereInput {
1071
+ id: ID!
1072
+ }
1073
+
1074
+ type Query {
1075
+ noteList(filter: NoteFilter, params: PaginationAndSorting): NoteResult
1076
+ noteGet(id: ID): NoteResult
1077
+ noteGetMany(ids: [ID]): NoteResult
1078
+ }
1079
+
1080
+ type Mutation {
1081
+ noteCreate(params: NoteInput): NoteResult
1082
+ noteUpdate(where: NoteWhereInput, params: NoteInput): NoteResult
1083
+ noteRemove(where: NoteWhereInput): NoteResult
1084
+ noteRemoveMany(where: [NoteWhereInput]): NoteResult
1085
+ }
1086
+ `;
1087
+
1088
+ export default typeDefs;
1089
+ ```
1090
+
1091
+ Generated resolvers:
1092
+
1093
+ | Resolver | Type | Core method |
1094
+ | --------------------- | -------- | ----------------------- |
1095
+ | `${prefix}List` | Query | `core.list(args)` |
1096
+ | `${prefix}Get` | Query | `core.get(args)` |
1097
+ | `${prefix}GetMany` | Query | `core.getMany(args)` |
1098
+ | `${prefix}Create` | Mutation | `core.create(args)` |
1099
+ | `${prefix}CreateMany` | Mutation | `core.createMany(args)` |
1100
+ | `${prefix}Update` | Mutation | `core.update(args)` |
1101
+ | `${prefix}UpdateMany` | Mutation | `core.updateMany(args)` |
1102
+ | `${prefix}Set` | Mutation | `core.set(args)` |
1103
+ | `${prefix}Remove` | Mutation | `core.remove(args)` |
1104
+ | `${prefix}RemoveMany` | Mutation | `core.removeMany(args)` |
1105
+
1106
+ ---
1107
+
1108
+ ## CLI utilities
1109
+
1110
+ Because all business logic lives in core classes, the same operations available over HTTP and GraphQL are equally accessible from a CLI command — with no duplication. The CLI simply constructs a context with synthetic request headers and calls core methods directly.
1111
+
1112
+ ### Project setup
1113
+
1114
+ Add a `cmd` script to `package.json` that points at your CLI entry point:
1115
+
1116
+ ```json
1117
+ {
1118
+ "scripts": {
1119
+ "cmd": "ts-node -r tsconfig-paths/register --project ./tsconfig.json ./src/app/cli/index.ts",
1120
+ "build": "cross-env NODE_ENV=production tsc -p ./tsconfig.json",
1121
+ "start": "node dist/src/index.js",
1122
+ "start:dev": "nodemon --exec \"ts-node -r tsconfig-paths/register --project ./tsconfig.json ./src/index.ts\" -e ts",
1123
+ "lint": "eslint */**/*.{js,ts,tsx} --quiet --fix",
1124
+ "test": "jest --config jest.config.ts",
1125
+ "create-migration": "knex migrate:make -x ts --knexfile ./src/knexConfig.ts",
1126
+ "migrations": "knex migrate:latest --knexfile ./src/knexConfig.ts",
1127
+ "migration-down": "knex migrate:down --knexfile ./src/knexConfig.ts",
1128
+ "rollback-migration": "knex migrate:rollback --knexfile ./src/knexConfig.ts",
1129
+ "seed": "knex seed:run --knexfile ./src/knexConfig.ts",
1130
+ "reset-db": "npm run cmd -- reset"
1131
+ }
1132
+ }
1133
+ ```
1134
+
1135
+ Usage:
1136
+
1137
+ ```bash
1138
+ npm run cmd -- reset # wipe DB, run migrations, seed
1139
+ npm run cmd -- recalculate # trigger a recalculation job
1140
+ npm run cmd -- fetch-recalls # fetch data from an external API
1141
+ npm run cmd -- --help # list all available commands
1142
+ ```
1143
+
1144
+ ### CLI entry point
1145
+
1146
+ ```typescript
1147
+ // src/app/cli/index.ts
1148
+ import yargs from 'yargs';
1149
+ import { HEADERS, dbReset } from '@sdflc/backend-helpers';
1150
+
1151
+ import { createContext } from '../../context';
1152
+ import config from '../../config';
1153
+ import knexHandle from '../../knexHandle';
1154
+ import { logger } from '../../logger';
1155
+ import { redisClient } from '../../redisClient';
1156
+
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
+ const getContext = () =>
1166
+ createContext({
1167
+ res: {},
1168
+ req: {
1169
+ socket: { remoteAddress: 'LOCAL' },
1170
+ headers: {
1171
+ [HEADERS.SPACE_ID]: 'develop',
1172
+ [HEADERS.API_KEY]: config.interserviceApiKey,
1173
+ [HEADERS.ACCOUNT_ID]: 'system',
1174
+ [HEADERS.USER_ID]: 'system',
1175
+ },
1176
+ },
1177
+ });
1178
+
1179
+ // ─── Commands ────────────────────────────────────────────────────────────────
1180
+
1181
+ const resetDb = () => {
1182
+ // dbReset is a standalone helper — does not need a context
1183
+ dbReset(knexHandle, config).then(() => knexHandle.destroy());
1184
+ };
1185
+
1186
+ const recalculateStats = async () => {
1187
+ const context = await getContext();
1188
+
1189
+ try {
1190
+ logger.log('Recalculating stats...');
1191
+ await context.cores.noteCore.recalculateAll({});
1192
+ logger.log('Done.');
1193
+ } finally {
1194
+ process.exit(0);
1195
+ }
1196
+ };
1197
+
1198
+ const syncExternalData = async () => {
1199
+ const context = await getContext();
1200
+
1201
+ try {
1202
+ // Connect Redis if available — some core operations use it for locking
1203
+ if (redisClient) {
1204
+ await redisClient.connect();
1205
+ }
1206
+
1207
+ logger.log('Syncing data from external API...');
1208
+ const result = await context.cores.noteCore.syncFromExternal({
1209
+ batchSize: 100,
1210
+ maxRecords: 10000,
1211
+ });
1212
+ logger.log('Sync result:', result?.data);
1213
+ logger.log('Done.');
1214
+ } finally {
1215
+ process.exit(0);
1216
+ }
1217
+ };
1218
+
1219
+ // ─── Command registration ─────────────────────────────────────────────────────
1220
+
1221
+ yargs(process.argv.splice(2))
1222
+ .command('reset', 'Wipes the database, runs all migrations, and seeds', () => {}, resetDb)
1223
+ .command('recalculate', 'Recalculates all stats and derived data', () => {}, recalculateStats)
1224
+ .command('sync', 'Syncs records from the external API', () => {}, syncExternalData)
1225
+ .strict()
1226
+ .help('h')
1227
+ .parse();
1228
+ ```
1229
+
1230
+ ### Key points
1231
+
1232
+ **Context reuse** — the same `createContext()` factory used by GraphQL and REST is used here. The CLI passes a synthetic `req` object with hardcoded headers to simulate a trusted system-level request. This means all authentication, gateway initialisation, and Redis/db wiring happens identically regardless of whether the caller is an HTTP client or a terminal.
1233
+
1234
+ **Interservice API key** — CLI commands typically bypass JWT auth by providing the `interserviceApiKey` in the synthetic headers. `BaseCore.authenticate()` recognises this key and grants access without a user token.
1235
+
1236
+ **Redis** — if a core operation requires Redis (e.g. for distributed locking or cache warming), connect `redisClient` before calling the core method. The `redisClient` is `null` when `REDIS_HOST` is not configured, so always check before connecting.
1237
+
1238
+ **Process exit** — CLI commands should call `process.exit(0)` in a `finally` block to ensure the Node.js process terminates cleanly after all async operations complete. Without it, open database connections and Redis clients can keep the process alive indefinitely.
1239
+
1240
+ **Database reset** — `dbReset` is a standalone helper that operates directly on a Knex handle without going through the context or any core. It is appropriate for destructive operations like wiping and re-migrating the database.
1241
+
1242
+ ---
1243
+
1244
+ ## Validation helpers
1245
+
1246
+ ### commonValidators
1247
+
1248
+ Pre-built validators aware of the core's `idType` setting.
1249
+
1250
+ ```typescript
1251
+ // src/core/validators/noteValidators.ts
1252
+ import Checkit from 'checkit';
1253
+ import {
1254
+ BaseCoreActionsInterface,
1255
+ validateList,
1256
+ validateCreate as validateCreateCommon,
1257
+ validateUpdate as validateUpdateCommon,
1258
+ } from '@sdflc/backend-helpers';
1259
+
1260
+ const rulesList = new Checkit({
1261
+ title: [{ rule: 'string', message: 'Title should be a string' }],
1262
+ });
1263
+
1264
+ const rulesCreate = new Checkit({
1265
+ title: [
1266
+ { rule: 'required', message: 'Title is required' },
1267
+ { rule: 'string', message: 'Title should be a string' },
1268
+ { rule: 'maxLength:256', message: 'Title must be under 256 characters' },
1269
+ ],
1270
+ body: [{ rule: 'string', message: 'Body should be a string' }],
1271
+ });
1272
+
1273
+ const rulesUpdate = new Checkit({
1274
+ title: [
1275
+ { rule: 'string', message: 'Title should be a string' },
1276
+ { rule: 'maxLength:256', message: 'Title must be under 256 characters' },
1277
+ ],
1278
+ });
1279
+
1280
+ const validateCreate = async (args: any, opt: BaseCoreActionsInterface) => {
1281
+ const [checkResult] = await validateCreateCommon({ rules: rulesCreate })(args, opt);
1282
+ if (checkResult !== true) return [checkResult, {}];
1283
+ return [true, {}];
1284
+ };
131
1285
 
132
- #### transformOnRemove(args?: any)
1286
+ const validateUpdate = async (args: any, opt: BaseCoreActionsInterface) => {
1287
+ const [checkResult] = await validateUpdateCommon({ rules: rulesUpdate })(args, opt);
1288
+ if (checkResult !== true) return [checkResult, {}];
1289
+ return [true, {}];
1290
+ };
1291
+
1292
+ export const validators = {
1293
+ list: validateList({ rules: rulesList }),
1294
+ create: validateCreate,
1295
+ update: validateUpdate,
1296
+ };
1297
+ ```
133
1298
 
134
- #### getDb()
1299
+ ---
135
1300
 
136
- #### getBuilder()
1301
+ ## Migration and seeding utilities
137
1302
 
138
- #### getIdField()
1303
+ ### DbMigratorAndSeeder
139
1304
 
140
- #### getCore()
1305
+ ```typescript
1306
+ import { DbMigratorAndSeeder } from '@sdflc/backend-helpers';
1307
+ import knexHandle from './knexHandle';
1308
+ import config from './config';
141
1309
 
142
- #### setCore(core: BaseCore)
1310
+ const migrator = new DbMigratorAndSeeder(knexHandle, {
1311
+ dbType: config.dbType,
1312
+ dbSchema: config.dbSchema,
1313
+ runDbSeed: true,
1314
+ });
143
1315
 
144
- #### get(id: any)
1316
+ await migrator.runMigrations();
1317
+ await migrator.resetDb();
1318
+ await migrator.cleanDb(['note', 'user']);
145
1319
 
146
- #### getMany(ids: any[])
1320
+ await migrator.runSeeds(__dirname, [['users'], ['notes', 'tags'], ['note_tags']]);
1321
+ ```
147
1322
 
148
- #### list(args?: ListArgsInterface)
1323
+ ### dbHelpers
149
1324
 
150
- #### create(args: any)
1325
+ ```typescript
1326
+ import { dbListTables, dbClean, dbRunMigrations, dbReset } from '@sdflc/backend-helpers';
151
1327
 
152
- #### update(where: any, params: any)
1328
+ // Used directly in CLI commands:
1329
+ await dbReset(knexHandle, config);
153
1330
 
154
- #### updateMany(params: any): Promise<any[]>
1331
+ const tables = await dbListTables(knexHandle, { dbType: 'pg', dbSchema: 'public', skipTables: ['migrations'] });
1332
+ await dbClean(tables, knexHandle, { dbSchema: 'public', dbType: 'pg' });
1333
+ await dbRunMigrations(knexHandle, { runDbSeed: false });
1334
+ ```
155
1335
 
156
- #### increment(where: any, params: any)
1336
+ ---
157
1337
 
158
- #### decrement(where: any, params: any)
1338
+ ## Field helpers
1339
+
1340
+ ```typescript
1341
+ import { dbFieldAddDefaults, addOrderNo, addUserId, defaultFields } from '@sdflc/backend-helpers';
1342
+
1343
+ exports.up = (knex: any) =>
1344
+ knex.schema.createTable('note', (table: any) => {
1345
+ table.uuid('id').primary().defaultTo(knex.raw('uuid_generate_v4()'));
1346
+ table.text('title').notNullable();
1347
+ table.text('body');
1348
+
1349
+ addUserId(table, { addIndex: true });
1350
+ addOrderNo(table, { addIndex: true });
1351
+
1352
+ dbFieldAddDefaults(table, {
1353
+ addStatus: true,
1354
+ addVersion: true,
1355
+ addUserInfo: true,
1356
+ });
1357
+ });
1358
+
1359
+ // In a seed file:
1360
+ const seedData = [{ id: 'seed-note-1', title: 'Hello world', ...defaultFields({ addUserInfo: true }) }];
1361
+ ```
1362
+
1363
+ ---
1364
+
1365
+ ## Utility functions
1366
+
1367
+ ### downloadFile
1368
+
1369
+ ```typescript
1370
+ import { downloadFile } from '@sdflc/backend-helpers';
1371
+
1372
+ const result = await downloadFile({
1373
+ url: 'https://example.com/report.pdf',
1374
+ folder: '/tmp/downloads',
1375
+ fileName: 'my-report.pdf',
1376
+ });
1377
+
1378
+ if (result.didSucceed()) {
1379
+ const { size, speed, durationMs } = result.getDataFirst();
1380
+ console.log(`Downloaded ${size} bytes at ${Math.round(speed)} B/s in ${durationMs}ms`);
1381
+ }
1382
+ ```
1383
+
1384
+ ### passwordHelpers
159
1385
 
160
- #### set(params: any): Promise<any[]>
1386
+ ```typescript
1387
+ import { getSaltAndHash, checkPassword } from '@sdflc/backend-helpers';
161
1388
 
162
- #### remove(where: any, hardRemove = false)
1389
+ const { hash } = await getSaltAndHash(plaintextPassword, 12);
1390
+ const isCorrect = await checkPassword(plaintextPassword, storedHash);
1391
+ ```
163
1392
 
164
- ### buildDefaultGatewayProps = (args: any)
1393
+ ---
165
1394
 
166
- This function builds configuration object for a gateways inherited from the BaseGateway classs
1395
+ ## Constants
167
1396
 
168
- ### BaseController
1397
+ ```typescript
1398
+ import { FIELDS, HEADERS, ORDER_BYS, ID_TYPES } from '@sdflc/backend-helpers';
169
1399
 
170
- Base constroller class is used to create request handlers for RESTful API and provides some methods to simplify the task of working with requests and responses
1400
+ FIELDS.ID; // 'id'
1401
+ FIELDS.STATUS; // 'status'
1402
+ FIELDS.CREATED_AT; // 'created_at'
1403
+ FIELDS.SPACE_ID; // 'space_id'
1404
+ FIELDS.USER_ID; // 'user_id'
1405
+ FIELDS.LANG; // 'lang'
1406
+ FIELDS.ORDER_NO; // 'order_no'
1407
+
1408
+ HEADERS.AUTHORIZATION; // 'authorization'
1409
+ HEADERS.SPACE_ID; // 'x-space-id'
1410
+ HEADERS.API_KEY; // 'x-api-key'
1411
+ HEADERS.FINGERPRINT; // 'x-fingerprint'
1412
+ HEADERS.IP_ADDRESS; // 'x-real-ip'
171
1413
 
172
- #### json(method: any)
1414
+ ID_TYPES.UNKNOWN; // 0
1415
+ ID_TYPES.INT; // 1
1416
+ ID_TYPES.UUID; // 2
1417
+ ID_TYPES.TEXT; // 3
173
1418
 
174
- ### Application Context
1419
+ ORDER_BYS.ASC; // 'asc'
1420
+ ORDER_BYS.DESC; // 'desc'
1421
+ ```
175
1422
 
176
- #### createApiContext = async (args: ApiContextInterface)
1423
+ ---
177
1424
 
178
- #### createContextDefault = async (args: any)
1425
+ ## Interfaces reference
1426
+
1427
+ | Interface | Description |
1428
+ | ----------------------------------------- | ------------------------------------------------------------------- |
1429
+ | `ApiContext` | Request context object shape |
1430
+ | `ApiContextInterface` | Arguments for `createApiContext()` |
1431
+ | `BaseCorePropsInterface` | Constructor props for `BaseCore` subclasses |
1432
+ | `BaseGatewayPropsInterface` | Constructor props for `BaseGateway` subclasses |
1433
+ | `BaseExternalApiGatewayPropsInterface` | Constructor props for `BaseExternalApiGateway` |
1434
+ | `BaseRestApiCrudControllerPropsInterface` | Constructor props for `BaseRestApiCrudController` |
1435
+ | `BuildDefaultResolvers` | Arguments for `buildDefaultResolvers()` |
1436
+ | `BuildConfigOptions` | Options for `buildConfig()` |
1437
+ | `DatabaseOptions` | Options for `Database` constructor |
1438
+ | `DatabaseReadInterface` | Arguments for `Database.read()` |
1439
+ | `CacheInterface` | Config for `DataCache` (without request context) |
1440
+ | `DataCachePropsInterface` | Full props for `DataCache` including request context |
1441
+ | `LoaderInterface` | Interface for custom loaders (`load`, `loadMany`, `clear`, `prime`) |
1442
+ | `CreateUserTokenArgs` | Options for `createUserToken()` |
1443
+ | `VerifyUserTokenArgs` | Options for `verifyUserToken()` |
1444
+ | `UserTokenParams` | JWT payload structure |
1445
+ | `DownloadFileArgs` | Arguments for `downloadFile()` |
1446
+ | `DbFieldAddDefaultInterface` | Options for `dbFieldAddDefaults()` |
1447
+ | `ListArgsInterface` | Standard list operation arguments |
1448
+ | `CoreActionInterface` | Arguments for `BaseCore.runAction()` including `tryAuth` |
1449
+
1450
+ ---
1451
+
1452
+ ## License
1453
+
1454
+ MIT