express-file-cluster 0.3.15 → 0.5.0
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 +71 -33
- package/dist/auth/index.cjs +12 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +13 -2
- package/dist/auth/index.d.ts +13 -2
- package/dist/auth/index.js +12 -2
- package/dist/chunk-3VWD2ZED.js +60 -0
- package/dist/chunk-3VWD2ZED.js.map +1 -0
- package/dist/chunk-47K2532L.cjs +196 -0
- package/dist/chunk-47K2532L.cjs.map +1 -0
- package/dist/chunk-5PDAWMGF.js +438 -0
- package/dist/chunk-5PDAWMGF.js.map +1 -0
- package/dist/chunk-7YEX4MQV.cjs +38 -0
- package/dist/chunk-7YEX4MQV.cjs.map +1 -0
- package/dist/chunk-ALBDM5R3.cjs +60 -0
- package/dist/chunk-ALBDM5R3.cjs.map +1 -0
- package/dist/chunk-JJJJTACK.js +196 -0
- package/dist/chunk-JJJJTACK.js.map +1 -0
- package/dist/chunk-LJNSJFOL.js +38 -0
- package/dist/chunk-LJNSJFOL.js.map +1 -0
- package/dist/chunk-M7MUPWCE.js +116 -0
- package/dist/chunk-M7MUPWCE.js.map +1 -0
- package/dist/chunk-PMF4GMHD.js +154 -0
- package/dist/chunk-PMF4GMHD.js.map +1 -0
- package/dist/chunk-QTRGJ2EN.cjs +2635 -0
- package/dist/chunk-QTRGJ2EN.cjs.map +1 -0
- package/dist/chunk-RSBW2B3D.cjs +126 -0
- package/dist/chunk-RSBW2B3D.cjs.map +1 -0
- package/dist/chunk-RTFJ32T5.js +2635 -0
- package/dist/chunk-RTFJ32T5.js.map +1 -0
- package/dist/chunk-SFVEQ2T5.cjs +438 -0
- package/dist/chunk-SFVEQ2T5.cjs.map +1 -0
- package/dist/chunk-SZT36SGB.cjs +154 -0
- package/dist/chunk-SZT36SGB.cjs.map +1 -0
- package/dist/chunk-TI24L4XE.cjs.map +1 -1
- package/dist/chunk-ULQXD4YZ.cjs +116 -0
- package/dist/chunk-ULQXD4YZ.cjs.map +1 -0
- package/dist/chunk-VYHJX54R.js +126 -0
- package/dist/chunk-VYHJX54R.js.map +1 -0
- package/dist/cli/db-runner.cjs +497 -0
- package/dist/cli/db-runner.cjs.map +1 -0
- package/dist/cli/db-runner.d.cts +2 -0
- package/dist/cli/db-runner.d.ts +2 -0
- package/dist/cli/db-runner.js +497 -0
- package/dist/cli/db-runner.js.map +1 -0
- package/dist/cli/index.cjs +447 -69
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +473 -95
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +232 -0
- package/dist/docs/api-reference/compose.md +78 -0
- package/dist/docs/api-reference/db.md +351 -0
- package/dist/docs/api-reference/http-error.md +109 -0
- package/dist/docs/api-reference/ignite.md +323 -0
- package/dist/docs/api-reference/table.md +250 -0
- package/dist/docs/api-reference/tasks.md +140 -0
- package/dist/docs/cli/db.md +38 -0
- package/dist/docs/cli/diagnostics.md +145 -0
- package/dist/docs/cli/generate.md +120 -0
- package/dist/docs/cli/index.md +48 -0
- package/dist/docs/cli/start.md +112 -0
- package/dist/docs/contributing/index.md +139 -0
- package/dist/docs/core-concepts/background-tasks.md +228 -0
- package/dist/docs/core-concepts/clustering.md +114 -0
- package/dist/docs/core-concepts/file-based-routing.md +235 -0
- package/dist/docs/core-concepts/index.md +79 -0
- package/dist/docs/core-concepts/middleware.md +144 -0
- package/dist/docs/getting-started/index.md +91 -0
- package/dist/docs/getting-started/project-structure.md +154 -0
- package/dist/docs/guides/ai-agents.md +48 -0
- package/dist/docs/guides/authentication.md +196 -0
- package/dist/docs/guides/caching.md +124 -0
- package/dist/docs/guides/database.md +217 -0
- package/dist/docs/guides/deployment.md +171 -0
- package/dist/docs/guides/environment-variables.md +106 -0
- package/dist/docs/guides/error-handling.md +172 -0
- package/dist/docs/guides/generated-portals.md +115 -0
- package/dist/docs/guides/logging.md +70 -0
- package/dist/docs/guides/mailer.md +166 -0
- package/dist/docs/guides/migrations.md +106 -0
- package/dist/docs/guides/rbac.md +89 -0
- package/dist/docs/guides/validation.md +95 -0
- package/dist/docs/index.md +93 -0
- package/dist/docs/skills/SKILL.md +44 -0
- package/dist/docs/skills/api-surface.md +308 -0
- package/dist/docs/skills/auth-internals.md +141 -0
- package/dist/docs/skills/pre-flight.md +142 -0
- package/dist/docs/skills/routing-rules.md +114 -0
- package/dist/docs/skills/tasks-internals.md +172 -0
- package/dist/docs/skills/what-not-to-invent.md +251 -0
- package/dist/index.cjs +289 -391
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +472 -7
- package/dist/index.d.ts +472 -7
- package/dist/index.js +283 -385
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-3E6ATY42.cjs +14 -0
- package/dist/pgboss-backend-3E6ATY42.cjs.map +1 -0
- package/dist/pgboss-backend-UUJOVEYK.js +14 -0
- package/dist/pgboss-backend-UUJOVEYK.js.map +1 -0
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/types-DJCPAsM4.d.cts +541 -0
- package/dist/types-DJCPAsM4.d.ts +541 -0
- package/package.json +28 -5
- package/dist/chunk-6522HS2J.cjs +0 -99
- package/dist/chunk-6522HS2J.cjs.map +0 -1
- package/dist/chunk-DGVOJNR6.cjs +0 -55
- package/dist/chunk-DGVOJNR6.cjs.map +0 -1
- package/dist/chunk-KOHLLUN7.js +0 -55
- package/dist/chunk-KOHLLUN7.js.map +0 -1
- package/dist/chunk-VIP3PFWZ.js +0 -99
- package/dist/chunk-VIP3PFWZ.js.map +0 -1
- package/dist/types-BusbSenn.d.cts +0 -162
- package/dist/types-BusbSenn.d.ts +0 -162
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
# `ignite(config)` — API Reference
|
|
2
|
+
|
|
3
|
+
`ignite()` is the single entry point that boots the framework. It handles clustering, database, auth, tasks, and routing in the correct order.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { ignite } from 'express-file-cluster';
|
|
7
|
+
|
|
8
|
+
const server = await ignite(config);
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
**Returns:** `Promise<http.Server | undefined>`
|
|
12
|
+
|
|
13
|
+
- Returns `http.Server` in a worker process (or in single-process mode).
|
|
14
|
+
- Returns `undefined` in the master process (clustering enabled, primary fork).
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## `EFCConfig` reference
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
interface EFCConfig {
|
|
22
|
+
// Routing
|
|
23
|
+
basePath?: string;
|
|
24
|
+
|
|
25
|
+
// Clustering
|
|
26
|
+
cluster?: boolean;
|
|
27
|
+
workers?: number;
|
|
28
|
+
onWorkerReady?: (id: number) => void;
|
|
29
|
+
onWorkerCrash?: (id: number, code: number) => void;
|
|
30
|
+
|
|
31
|
+
// Database
|
|
32
|
+
database?: 'mongodb' | 'postgresql';
|
|
33
|
+
databaseUrl?: string;
|
|
34
|
+
|
|
35
|
+
// Auth
|
|
36
|
+
authStrategy?: 'http-only' | 'localStorage';
|
|
37
|
+
jwtSecret?: string;
|
|
38
|
+
jwtExpiresIn?: string;
|
|
39
|
+
cookieDomain?: string;
|
|
40
|
+
|
|
41
|
+
// Background tasks
|
|
42
|
+
tasks?: TaskConfig | false;
|
|
43
|
+
|
|
44
|
+
// HTTP
|
|
45
|
+
port?: number;
|
|
46
|
+
cors?: boolean | CorsConfig;
|
|
47
|
+
requestTimeout?: number;
|
|
48
|
+
globalMiddlewares?: RequestHandler[];
|
|
49
|
+
onError?: ErrorRequestHandler;
|
|
50
|
+
|
|
51
|
+
// Logging
|
|
52
|
+
logging?: LoggingConfig | false;
|
|
53
|
+
|
|
54
|
+
// Reconcile tables/collections + indexes on first use (default true)
|
|
55
|
+
autoSync?: boolean;
|
|
56
|
+
|
|
57
|
+
// Cache + session revocation store
|
|
58
|
+
cache?: CacheConfig | false;
|
|
59
|
+
|
|
60
|
+
// Developer tools
|
|
61
|
+
dashboard?: boolean;
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Option details
|
|
68
|
+
|
|
69
|
+
### `basePath`
|
|
70
|
+
|
|
71
|
+
URL prefix prepended to every route. Default: `'/v1/api'`.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
ignite({ basePath: '/api' });
|
|
75
|
+
// routes: /api/health, /api/users/:id, ...
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Set to `'/'` to mount routes directly at the root with no prefix.
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
### `dashboard`
|
|
83
|
+
|
|
84
|
+
When `true`, EFC mounts a live API documentation page at `GET /` (or `GET <basePath>/`) that is only active in development (`NODE_ENV === 'development'`). The page lists every registered route with its method, path, description, and request/response examples derived from each file's `meta` export.
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
ignite({ dashboard: true });
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
### `port`
|
|
93
|
+
|
|
94
|
+
HTTP listen port. Default: `3000`. `ignite()` never reads `PORT` from the environment itself — pass it explicitly, typically by reading `process.env.PORT` in `efc.config.ts` (see [Environment Variables](../guides/environment-variables.md)).
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
ignite({ port: 8080 });
|
|
98
|
+
// or, in efc.config.ts: port: process.env.PORT ? Number(process.env.PORT) : undefined
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
### `cluster`
|
|
104
|
+
|
|
105
|
+
Enable multi-core clustering. When `true`, the primary process forks `workers` child processes and returns `undefined`. Each worker runs the full Pre-Flight lifecycle independently.
|
|
106
|
+
|
|
107
|
+
Default: `true` when `NODE_ENV === 'production'`, `false` otherwise.
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
ignite({ cluster: true, workers: 4 });
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
### `workers`
|
|
116
|
+
|
|
117
|
+
Number of worker processes to fork. Default: `os.cpus().length`.
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
### `onWorkerReady`
|
|
122
|
+
|
|
123
|
+
Called by the primary process when a worker emits the `'online'` event.
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
onWorkerReady: (id) => logger.info(`Worker ${id} is live`),
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
### `onWorkerCrash`
|
|
132
|
+
|
|
133
|
+
Called by the primary process when a worker exits unexpectedly, before a replacement is forked. The `code` is the exit code (or `-1` if the worker was killed by a signal).
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
onWorkerCrash: (id, code) => alerting.send(`Worker ${id} crashed with code ${code}`),
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
---
|
|
140
|
+
|
|
141
|
+
### `database`
|
|
142
|
+
|
|
143
|
+
Database engine to connect. When omitted, EFC detects it from the `databaseUrl` scheme (`mongodb://…` / `mongodb+srv://…` → `'mongodb'`, `postgres://…` / `postgresql://…` → `'postgresql'`). The engine also decides what [`defineModel`](./db.md) compiles to: a mongoose model or a Drizzle table. MongoDB needs `mongoose` installed; PostgreSQL needs `pg` and `drizzle-orm`.
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
### `databaseUrl`
|
|
148
|
+
|
|
149
|
+
Connection string for the database. `ignite()` never reads `DATABASE_URL` from the environment itself — pass it explicitly (typically `databaseUrl: process.env.DATABASE_URL` in `efc.config.ts`).
|
|
150
|
+
|
|
151
|
+
---
|
|
152
|
+
|
|
153
|
+
### `authStrategy`
|
|
154
|
+
|
|
155
|
+
How JWTs are delivered to clients:
|
|
156
|
+
|
|
157
|
+
| Value | Mechanism |
|
|
158
|
+
|---|---|
|
|
159
|
+
| `'http-only'` | `HttpOnly + Secure + SameSite=Strict` cookie named `efc_token` |
|
|
160
|
+
| `'localStorage'` | Token returned in response body; client attaches `Authorization: Bearer <token>` |
|
|
161
|
+
|
|
162
|
+
Default: `'http-only'`.
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
### `jwtSecret`
|
|
167
|
+
|
|
168
|
+
Secret used to sign and verify JWTs (HS256). `ignite()` never reads `JWT_SECRET` from the environment itself — pass it explicitly (typically `jwtSecret: process.env.JWT_SECRET` in `efc.config.ts`). Must be at least 32 random bytes for production use.
|
|
169
|
+
|
|
170
|
+
---
|
|
171
|
+
|
|
172
|
+
### `jwtExpiresIn`
|
|
173
|
+
|
|
174
|
+
Token lifetime, e.g. `'15m'`, `'1h'`, `'7d'`, `'30d'`. Default: `'7d'`. Pass explicitly (typically `jwtExpiresIn: process.env.JWT_EXPIRES_IN`); no environment fallback.
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
### `cookieDomain`
|
|
179
|
+
|
|
180
|
+
Cookie domain used by the `'http-only'` auth strategy. Default: unset (host-only cookie, correct for `localhost`). Pass explicitly (typically `cookieDomain: process.env.COOKIE_DOMAIN`); no environment fallback.
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
### `tasks`
|
|
185
|
+
|
|
186
|
+
Background task runtime configuration. Set to `false` (or omit) to disable the task system.
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
interface TaskConfig {
|
|
190
|
+
backend: 'bullmq' | 'pg-boss';
|
|
191
|
+
redisUrl?: string; // BullMQ — default redis://localhost:6379
|
|
192
|
+
connectionString?: string; // pg-boss — default: databaseUrl
|
|
193
|
+
schema?: string; // pg-boss — Postgres schema for its tables, default 'pgboss'
|
|
194
|
+
concurrency?: number; // jobs processed in parallel per worker — default 5
|
|
195
|
+
enqueueTimeout?: number; // max ms enqueue() waits for the backend before rejecting — default 5000
|
|
196
|
+
queue?: string; // queue name; apps sharing a Redis DB / Postgres need distinct ones — default 'efc'
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
See [Background Tasks](../core-concepts/background-tasks.md).
|
|
201
|
+
|
|
202
|
+
---
|
|
203
|
+
|
|
204
|
+
### `logging`
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
interface LoggingConfig {
|
|
208
|
+
level?: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'silent'; // default 'info'
|
|
209
|
+
pretty?: boolean; // default: true in a non-production TTY, JSON otherwise
|
|
210
|
+
requests?: boolean; // one line per completed request — default true
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
`false` silences framework logs. Every request still gets an `X-Request-Id`. See [Logging](../guides/logging.md).
|
|
215
|
+
|
|
216
|
+
---
|
|
217
|
+
|
|
218
|
+
### `cors`
|
|
219
|
+
|
|
220
|
+
CORS configuration. Default: `true` (allow all origins). `ignite()` never reads `CORS_ORIGINS` from the environment itself — pass `cors.origin` explicitly.
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
ignite({
|
|
224
|
+
cors: {
|
|
225
|
+
// typically built from `process.env.CORS_ORIGINS?.split(',').map(o => o.trim())`
|
|
226
|
+
// in efc.config.ts — pass an array (not a bare string) so per-request Origin
|
|
227
|
+
// validation actually happens instead of a single static header value
|
|
228
|
+
origin: ['https://app.example.com', 'https://admin.example.com'],
|
|
229
|
+
credentials: true,
|
|
230
|
+
maxAge: 86400,
|
|
231
|
+
},
|
|
232
|
+
});
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Set `cors: false` to skip CORS headers entirely.
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
interface CorsConfig {
|
|
239
|
+
origin?: string | string[] | boolean;
|
|
240
|
+
methods?: string | string[];
|
|
241
|
+
allowedHeaders?: string | string[];
|
|
242
|
+
credentials?: boolean;
|
|
243
|
+
maxAge?: number;
|
|
244
|
+
}
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
---
|
|
248
|
+
|
|
249
|
+
### `cache`
|
|
250
|
+
|
|
251
|
+
```ts
|
|
252
|
+
type CacheConfig = { prefix?: string; onRevocationCheckError?: 'reject' | 'allow' } & (
|
|
253
|
+
| { backend: 'redis'; url?: string; timeout?: number }
|
|
254
|
+
| { backend: 'memory'; maxEntries?: number } // shared by this machine's cluster workers via the primary
|
|
255
|
+
);
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
`onRevocationCheckError` (default `'reject'`): when the cache can't be reached for a revocation check, `requireAuth` answers 503 (`'reject'`) or lets the request through (`'allow'`).
|
|
259
|
+
|
|
260
|
+
Enables `cache`, `cacheResponse()` and session revocation (`revokeSession`, `revokeAllSessions`). Connected during Pre-Flight, after the database. See [Caching & Sessions](../guides/caching.md).
|
|
261
|
+
|
|
262
|
+
---
|
|
263
|
+
|
|
264
|
+
### `autoSync`
|
|
265
|
+
|
|
266
|
+
Default `true`: the first time each model is used in a process, its table (PostgreSQL) or collection and indexes (MongoDB) are reconciled with the definition — see [Database](../guides/database.md#the-schema-takes-care-of-itself). Set `false` to change the schema only through `efc db sync` / migrations; on MongoDB this also turns off mongoose's `autoIndex` / `autoCreate`.
|
|
267
|
+
|
|
268
|
+
---
|
|
269
|
+
|
|
270
|
+
### `requestTimeout`
|
|
271
|
+
|
|
272
|
+
Milliseconds a request may take before EFC answers **408** `{ "error": "Request Timeout", "statusCode": 408 }`. A handler that keeps running and replies later is ignored (logged at `warn`) instead of crashing. Default: no timeout.
|
|
273
|
+
|
|
274
|
+
---
|
|
275
|
+
|
|
276
|
+
### `globalMiddlewares`
|
|
277
|
+
|
|
278
|
+
Array of Express `RequestHandler` functions applied to every route, in order, before route-level middleware.
|
|
279
|
+
|
|
280
|
+
```ts
|
|
281
|
+
ignite({
|
|
282
|
+
globalMiddlewares: [requestLogger, rateLimiter],
|
|
283
|
+
});
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
---
|
|
287
|
+
|
|
288
|
+
### `onError`
|
|
289
|
+
|
|
290
|
+
Override the built-in global error handler. Receives `(err, req, res, next)`. If not provided, EFC responds with:
|
|
291
|
+
|
|
292
|
+
- `{ error: err.message, statusCode: err.statusCode }` for `HttpError` instances.
|
|
293
|
+
- `{ error: 'Internal Server Error', statusCode: 500 }` for all other errors.
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
ignite({
|
|
297
|
+
onError: (err, req, res, _next) => {
|
|
298
|
+
logger.error({ err, url: req.url });
|
|
299
|
+
const status = (err as any).statusCode ?? 500;
|
|
300
|
+
res.status(status).json({ error: err.message });
|
|
301
|
+
},
|
|
302
|
+
});
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
---
|
|
306
|
+
|
|
307
|
+
## `gracefulShutdown(server, timeoutMs?)`
|
|
308
|
+
|
|
309
|
+
Registers `SIGTERM` and `SIGINT` handlers for clean shutdown. Pass the `http.Server` returned by `ignite()`.
|
|
310
|
+
|
|
311
|
+
```ts
|
|
312
|
+
ignite({ port: 3000 })
|
|
313
|
+
.then(gracefulShutdown);
|
|
314
|
+
// or with a custom timeout:
|
|
315
|
+
.then((server) => gracefulShutdown(server, 30_000));
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
| Parameter | Type | Default | Description |
|
|
319
|
+
|---|---|---|---|
|
|
320
|
+
| `server` | `http.Server \| undefined` | — | Server to close (undefined for the master process) |
|
|
321
|
+
| `timeoutMs` | `number` | `10_000` | Force-exit after this many milliseconds if `server.close()` hasn't finished |
|
|
322
|
+
|
|
323
|
+
On a worker, the signal closes the HTTP server (in-flight requests finish), drains running task jobs, then exits. On the cluster primary it relays `SIGTERM` to every worker — so `docker stop` / Kubernetes, which signal only PID 1, still shut down gracefully — and force-exits after `timeoutMs + 2s` if a worker hangs. Repeated signals are ignored rather than killing a worker mid-drain.
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
# defineTable — API Reference
|
|
2
|
+
|
|
3
|
+
```ts
|
|
4
|
+
import { defineTable, type InferRecord } from 'express-file-cluster';
|
|
5
|
+
```
|
|
6
|
+
|
|
7
|
+
`defineTable` is EFC's **PostgreSQL-native** model API. It uses Prisma's query vocabulary
|
|
8
|
+
(`findMany({ where, orderBy, take, cursor })`, `findUnique`, `upsert`, `groupBy`, `aggregate`)
|
|
9
|
+
and SQL types (`integer`, `bigint`, `decimal`, `varchar`, native arrays and enums, serial ids).
|
|
10
|
+
Each call is a single parameterised SQL statement.
|
|
11
|
+
|
|
12
|
+
It shares the foundation with [`defineModel`](./db.md): the same schema format, validation,
|
|
13
|
+
automatic table sync, `transaction()`, errors and inferred types. Choose between them:
|
|
14
|
+
|
|
15
|
+
| | `defineModel` | `defineTable` |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| Engine | MongoDB **or** PostgreSQL | PostgreSQL only |
|
|
18
|
+
| Queries | MongoDB-style (`find(filter)`, `$gt`, `$inc`) | Prisma-style (`findMany({ where })`, `gt`, `increment`) |
|
|
19
|
+
| Types | portable set | + `integer`, `bigint`, `decimal`, `uuid`, `json`, `varchar`, native arrays/enums |
|
|
20
|
+
| Use it when | the app may switch engines | you're building on PostgreSQL |
|
|
21
|
+
|
|
22
|
+
On a MongoDB connection, the first call to a `defineTable` model throws an `[EFC]` error.
|
|
23
|
+
Calling a MongoDB-style method on a table (or a Prisma-style one on a `defineModel`) is a
|
|
24
|
+
compile error. A `defineModel` and a `defineTable` over the same table read and write the same
|
|
25
|
+
records (default naming, uuid ids), so you can move one model at a time.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## `defineTable(name, schema, options?)`
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
export const Order = defineTable(
|
|
33
|
+
'Order',
|
|
34
|
+
{
|
|
35
|
+
number: { type: 'string', required: true, unique: true, maxLength: 20 }, // varchar(20)
|
|
36
|
+
status: { type: 'string', enum: ['open', 'paid', 'shipped'], default: 'open', nativeEnum: true },
|
|
37
|
+
total: { type: 'decimal', precision: 10, scale: 2, required: true }, // numeric(10,2) → '19.99'
|
|
38
|
+
qty: { type: 'integer', required: true, min: 1 }, // integer
|
|
39
|
+
views: { type: 'bigint', default: 0n }, // bigint → 0n
|
|
40
|
+
tags: { type: 'array', of: 'string', default: [] }, // text[]
|
|
41
|
+
shipping: { city: { type: 'string', required: true }, zip: { type: 'string' } }, // jsonb
|
|
42
|
+
meta: { type: 'json' }, // jsonb, any JSON
|
|
43
|
+
customer: { type: 'uuid', required: true },
|
|
44
|
+
},
|
|
45
|
+
{ id: 'serial', naming: 'snake_case', indexes: [{ fields: { customer: 1, number: 1 }, unique: true }] },
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
export type Order = InferRecord<typeof Order>;
|
|
49
|
+
// { id: number; number: string; status: 'open' | 'paid' | 'shipped'; total: string; qty: number;
|
|
50
|
+
// views: bigint; tags: string[]; customer: string; shipping?: { city: string; zip?: string };
|
|
51
|
+
// meta?: unknown; createdAt: Date; updatedAt: Date }
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### Field types
|
|
55
|
+
|
|
56
|
+
All the [`defineModel` field types and rules](./db.md#schema-fields) (`required`, `default`,
|
|
57
|
+
`enum`, `min`/`max`, `minLength`/`maxLength`, `match`, `validate`, `unique`, `index`,
|
|
58
|
+
`sequence`, nested objects, arrays of objects) also work here, plus:
|
|
59
|
+
|
|
60
|
+
| `type` | Column | JS value (reads) | Accepts on writes |
|
|
61
|
+
|---|---|---|---|
|
|
62
|
+
| `'integer'` | `integer` | `number` (32-bit, whole) | `number` |
|
|
63
|
+
| `'bigint'` | `bigint` | `bigint` | `bigint \| number` |
|
|
64
|
+
| `'decimal'` (`precision`, `scale`) | `numeric(p,s)` | `string`, exact | `string \| number` |
|
|
65
|
+
| `'uuid'` | `uuid` | `string` | `string` |
|
|
66
|
+
| `'json'` | `jsonb` | `unknown` | any JSON |
|
|
67
|
+
| `'string'` + `maxLength` | `varchar(n)` | `string` | `string` |
|
|
68
|
+
| `{ type: 'array', of: <scalar> }` | native array (`text[]`, `integer[]`, …) | `T[]` | `T[]` |
|
|
69
|
+
| `enum` + `nativeEnum: true` | PostgreSQL `ENUM` type | literal union | literal union |
|
|
70
|
+
|
|
71
|
+
Without `nativeEnum`, an `enum` is a `CHECK` constraint, as with `defineModel`. Arrays of nested
|
|
72
|
+
objects, embedded objects and `json` are stored as `jsonb`. `column: 'name'` sets a top-level
|
|
73
|
+
field's column name.
|
|
74
|
+
|
|
75
|
+
Responses from `ignite()` serialise `bigint` values as strings (`"9007199254740993"`).
|
|
76
|
+
|
|
77
|
+
### Options
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
interface TableOptions {
|
|
81
|
+
id?: 'uuid' | 'serial' | 'bigserial'; // default 'uuid'; serial → number ids, bigserial → bigint ids
|
|
82
|
+
naming?: 'snake_case'; // createdAt → created_at, OrderItem → order_items
|
|
83
|
+
timestamps?: boolean | { createdAt?: string | false; updatedAt?: string | false };
|
|
84
|
+
indexes?: { fields: Record<string, 1 | -1 | 'text'>; unique?: boolean; name?: string }[];
|
|
85
|
+
collection?: string; // table name
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Schema sync
|
|
90
|
+
|
|
91
|
+
The table is created and kept in step on first use, with the same rules as `defineModel`. It
|
|
92
|
+
never drops columns or rows. On top of that:
|
|
93
|
+
|
|
94
|
+
- Native enum types are created, and new values are added. Values are never removed.
|
|
95
|
+
- `varchar` columns never shrink, and an existing `text` column is never narrowed.
|
|
96
|
+
- An existing `jsonb` array column (e.g. from `defineModel`) is converted to a native array,
|
|
97
|
+
keeping the data.
|
|
98
|
+
|
|
99
|
+
Preview the changes with `efc db sync --dry-run`.
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## Reading
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
findMany(args?) → Record[]
|
|
107
|
+
findFirst(args?) → Record | null
|
|
108
|
+
findFirstOrThrow(args?) → Record // 404 HttpError if none
|
|
109
|
+
findUnique({ where }) → Record | null // where must name a unique key
|
|
110
|
+
findUniqueOrThrow({ where }) → Record // 404 HttpError if none
|
|
111
|
+
count(args?) → number // or { _all, field… } with select
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
const page = await Order.findMany({
|
|
116
|
+
where: {
|
|
117
|
+
status: { in: ['paid', 'shipped'] },
|
|
118
|
+
total: { gte: '100' },
|
|
119
|
+
customer: id,
|
|
120
|
+
OR: [{ number: { startsWith: 'EU-' } }, { tags: { has: 'priority' } }],
|
|
121
|
+
},
|
|
122
|
+
orderBy: [{ createdAt: 'desc' }, { qty: { sort: 'asc', nulls: 'last' } }],
|
|
123
|
+
take: 20,
|
|
124
|
+
skip: 20,
|
|
125
|
+
select: { id: true, number: true, total: true }, // result type narrows to these
|
|
126
|
+
});
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
| Argument | |
|
|
130
|
+
|---|---|
|
|
131
|
+
| `where` | filters (below) |
|
|
132
|
+
| `orderBy` | `{ field: 'asc' \| 'desc' }`, `{ field: { sort, nulls: 'first' \| 'last' } }`, or an array |
|
|
133
|
+
| `take` / `skip` | page size / offset. A negative `take` reads backwards. |
|
|
134
|
+
| `cursor` | a unique `where` (`{ id }`). The page starts **at** that record; add `skip: 1` to start after it. |
|
|
135
|
+
| `distinct` | `['field', …]`: the first record per distinct combination, in `orderBy` order |
|
|
136
|
+
| `select` / `omit` | `{ field: true }`: keep, or leave out, these fields. The result type follows. |
|
|
137
|
+
|
|
138
|
+
Pages are ordered deterministically: when `take`, `skip` or `cursor` is used, ties are broken
|
|
139
|
+
by `id`. Cursors work with any `orderBy`, including mixed directions and nullable columns.
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
// Cursor pagination
|
|
143
|
+
const next = await Order.findMany({ orderBy: { qty: 'desc' }, take: 20, cursor: { id: last }, skip: 1 });
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### Filters
|
|
147
|
+
|
|
148
|
+
| Field kind | Filters |
|
|
149
|
+
|---|---|
|
|
150
|
+
| any scalar | a value (equality), `null`, `equals`, `not`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte` |
|
|
151
|
+
| strings | + `contains`, `startsWith`, `endsWith`, `mode: 'insensitive'` (ILIKE) |
|
|
152
|
+
| native arrays | `has`, `hasEvery`, `hasSome`, `isEmpty`, `equals` |
|
|
153
|
+
| objects / arrays of objects / `json` | `equals`, `not`, and with `path: ['a', 'b']`: `equals`, `string_contains`, `string_starts_with`, `string_ends_with`, `array_contains`, `gt`… |
|
|
154
|
+
| combinators | `AND`, `OR`, `NOT` (an object or an array) |
|
|
155
|
+
|
|
156
|
+
`undefined` values are ignored. Filters on undeclared fields match nothing, as with
|
|
157
|
+
`defineModel`. `LIKE` wildcards in `contains`, `startsWith` and `endsWith` are escaped.
|
|
158
|
+
|
|
159
|
+
### Unique lookups
|
|
160
|
+
|
|
161
|
+
`findUnique`, `update`, `upsert`, `delete` and `cursor` take a `where` that names one record:
|
|
162
|
+
`id`, a `unique: true` field, or every field of a `unique` index (e.g. `{ customer, number }`).
|
|
163
|
+
Other filters may be added. A `where` that isn't unique doesn't compile, and at runtime it
|
|
164
|
+
throws a `ModelValidationError`.
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
## Writing
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
create({ data, select?, omit? }) → Record
|
|
172
|
+
createMany({ data: [...], skipDuplicates? }) → { count }
|
|
173
|
+
createManyAndReturn({ data: [...], select? }) → Record[]
|
|
174
|
+
update({ where: unique, data, select? }) → Record // 404 if missing
|
|
175
|
+
updateMany({ where?, data }) → { count }
|
|
176
|
+
updateManyAndReturn({ where?, data, select? }) → Record[]
|
|
177
|
+
upsert({ where: unique, create, update, select? }) → Record
|
|
178
|
+
delete({ where: unique }) → Record // 404 if missing
|
|
179
|
+
deleteMany({ where? }) → { count }
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
await Order.update({
|
|
184
|
+
where: { number: 'EU-1' },
|
|
185
|
+
data: {
|
|
186
|
+
status: 'paid',
|
|
187
|
+
qty: { increment: 1 }, // decrement, multiply, divide — number fields
|
|
188
|
+
views: { increment: 1n },
|
|
189
|
+
total: { decrement: '5.00' }, // exact on decimals
|
|
190
|
+
tags: { push: 'priority' }, // or an array; on native arrays
|
|
191
|
+
shipping: { city: 'Oslo' }, // jsonb fields take whole values
|
|
192
|
+
meta: null, // null unsets an optional field
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
- **`upsert`** is a single `INSERT … ON CONFLICT (<unique key>) DO UPDATE`, so it's atomic and
|
|
198
|
+
race-free. Key values from `where` fill `create` when they're missing there.
|
|
199
|
+
- **`createMany({ skipDuplicates: true })`** → `ON CONFLICT DO NOTHING`.
|
|
200
|
+
- Writes are validated like `defineModel` writes: type, `enum`, bounds, `integer` range,
|
|
201
|
+
`decimal` precision/scale, `maxLength` and `validate`. Failures throw `ModelValidationError`
|
|
202
|
+
(400); a duplicate unique value gives a 409. `updatedAt` is refreshed on every update.
|
|
203
|
+
`increment`/`decrement` results are not re-checked against `min`/`max`.
|
|
204
|
+
|
|
205
|
+
---
|
|
206
|
+
|
|
207
|
+
## Aggregation
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
const stats = await Order.aggregate({
|
|
211
|
+
where: { status: 'paid' },
|
|
212
|
+
_count: true,
|
|
213
|
+
_sum: { total: true, qty: true },
|
|
214
|
+
_avg: { qty: true },
|
|
215
|
+
_min: { createdAt: true },
|
|
216
|
+
_max: { total: true },
|
|
217
|
+
});
|
|
218
|
+
// { _count: number; _sum: { total: string | null; qty: number | null }; _avg: { qty: number | null };
|
|
219
|
+
// _min: { createdAt: Date | null }; _max: { total: string | null } }
|
|
220
|
+
|
|
221
|
+
const byStatus = await Order.groupBy({
|
|
222
|
+
by: ['status'],
|
|
223
|
+
where: { createdAt: { gte: since } },
|
|
224
|
+
_count: { _all: true },
|
|
225
|
+
_sum: { total: true },
|
|
226
|
+
having: { total: { _sum: { gt: 1000 } } },
|
|
227
|
+
orderBy: { _sum: { total: 'desc' } },
|
|
228
|
+
take: 10,
|
|
229
|
+
});
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
| Aggregate | Applies to | Returns |
|
|
233
|
+
|---|---|---|
|
|
234
|
+
| `_count` | `true` or `{ _all, field }` | `number` (non-null values per field) |
|
|
235
|
+
| `_sum` | number fields | `integer`/`number` → `number`, `bigint` → `bigint`, `decimal` → `string` |
|
|
236
|
+
| `_avg` | number fields | `number`; `decimal` → `string` |
|
|
237
|
+
| `_min` / `_max` | scalar fields | the field's type |
|
|
238
|
+
|
|
239
|
+
Over an empty set, `_sum`, `_avg`, `_min` and `_max` are `null`. `aggregate` also takes
|
|
240
|
+
`orderBy`, `take`, `skip` and `cursor`, and then aggregates over that page.
|
|
241
|
+
|
|
242
|
+
---
|
|
243
|
+
|
|
244
|
+
## Also
|
|
245
|
+
|
|
246
|
+
- `raw()` returns the Drizzle `pgTable`, for anything EFC doesn't cover.
|
|
247
|
+
- `sync({ dryRun })` / `drop()` work as with `defineModel`.
|
|
248
|
+
- `transaction(async () => …)` covers `defineTable` calls too.
|
|
249
|
+
- Relations (`include`, foreign keys, relation filters, nested writes) are planned (M3), not
|
|
250
|
+
implemented yet.
|