express-file-cluster 0.3.15 → 0.7.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-277BSYVH.js +127 -0
- package/dist/chunk-277BSYVH.js.map +1 -0
- package/dist/chunk-6OGOVV57.js +3847 -0
- package/dist/chunk-6OGOVV57.js.map +1 -0
- package/dist/chunk-7YEX4MQV.cjs +38 -0
- package/dist/chunk-7YEX4MQV.cjs.map +1 -0
- package/dist/chunk-AZYXQU3Z.cjs +3847 -0
- package/dist/chunk-AZYXQU3Z.cjs.map +1 -0
- package/dist/chunk-BUBXO7WU.js +170 -0
- package/dist/chunk-BUBXO7WU.js.map +1 -0
- package/dist/chunk-LJNSJFOL.js +38 -0
- package/dist/chunk-LJNSJFOL.js.map +1 -0
- package/dist/chunk-MGH4VDV3.cjs +170 -0
- package/dist/chunk-MGH4VDV3.cjs.map +1 -0
- package/dist/chunk-R34R7QPD.cjs +116 -0
- package/dist/chunk-R34R7QPD.cjs.map +1 -0
- package/dist/chunk-RS4MXCPW.js +116 -0
- package/dist/chunk-RS4MXCPW.js.map +1 -0
- package/dist/chunk-T4OHFU5T.cjs +154 -0
- package/dist/chunk-T4OHFU5T.cjs.map +1 -0
- package/dist/chunk-TI24L4XE.cjs.map +1 -1
- package/dist/chunk-TRC4DUZB.js +438 -0
- package/dist/chunk-TRC4DUZB.js.map +1 -0
- package/dist/chunk-TYR2GZZE.cjs +196 -0
- package/dist/chunk-TYR2GZZE.cjs.map +1 -0
- package/dist/chunk-UBQYQPBU.js +154 -0
- package/dist/chunk-UBQYQPBU.js.map +1 -0
- package/dist/chunk-UTM4PEVG.js +196 -0
- package/dist/chunk-UTM4PEVG.js.map +1 -0
- package/dist/chunk-YL37D6KM.cjs +127 -0
- package/dist/chunk-YL37D6KM.cjs.map +1 -0
- package/dist/chunk-ZDM5JHVK.cjs +438 -0
- package/dist/chunk-ZDM5JHVK.cjs.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 +326 -0
- package/dist/docs/api-reference/table.md +458 -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 +108 -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 +309 -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 +264 -391
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +699 -7
- package/dist/index.d.ts +699 -7
- package/dist/index.js +258 -385
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-QKBXVJ6B.js +14 -0
- package/dist/pgboss-backend-QKBXVJ6B.js.map +1 -0
- package/dist/pgboss-backend-TCHI7CHM.cjs +14 -0
- package/dist/pgboss-backend-TCHI7CHM.cjs.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-B6lVw4bj.d.cts +588 -0
- package/dist/types-B6lVw4bj.d.ts +588 -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,351 @@
|
|
|
1
|
+
# Database — API Reference
|
|
2
|
+
|
|
3
|
+
```ts
|
|
4
|
+
import { defineModel, transaction, db, ModelValidationError } from 'express-file-cluster';
|
|
5
|
+
import type { InferRecord, InferCreate } from 'express-file-cluster';
|
|
6
|
+
```
|
|
7
|
+
|
|
8
|
+
`defineModel` gives one model API on **MongoDB** (mongoose) and **PostgreSQL** (Drizzle). The model compiles for whichever engine Pre-Flight connected — `database` in `ignite()`, or the `DATABASE_URL` scheme — the first time it is used, so models can be defined at import time. One conformance test suite runs every feature below against both engines.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## `defineModel(name, schema, options?)`
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
function defineModel(name: string, schema: ModelSchema, options?: ModelOptions): ModelCRUD<Record, CreateInput>
|
|
16
|
+
// record and create-input types are inferred from the schema literal
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
| Parameter | Description |
|
|
20
|
+
|---|---|
|
|
21
|
+
| `name` | Model name. Also the `ref` target for references. The collection/table defaults to its lowercase plural (`User` → `users`, `Category` → `categories`). |
|
|
22
|
+
| `schema` | Field definitions (below). |
|
|
23
|
+
| `options` | Timestamps, indexes, collection/table name. |
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { defineModel, type InferRecord } from 'express-file-cluster';
|
|
27
|
+
|
|
28
|
+
export const Order = defineModel(
|
|
29
|
+
'Order',
|
|
30
|
+
{
|
|
31
|
+
number: { type: 'number', sequence: true },
|
|
32
|
+
status: { type: 'string', enum: ['pending', 'paid', 'shipped'], default: 'pending', index: true },
|
|
33
|
+
customer: { type: 'objectId', ref: 'Customer', required: true },
|
|
34
|
+
items: [{ sku: { type: 'string', required: true }, qty: { type: 'number', min: 1 } }],
|
|
35
|
+
shipping: { city: { type: 'string', required: true }, zip: { type: 'string', match: /^\d{5}$/ } },
|
|
36
|
+
tags: { type: 'array', of: 'string', default: [] },
|
|
37
|
+
},
|
|
38
|
+
{ indexes: [{ fields: { customer: 1, createdAt: -1 } }] },
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
export type Order = InferRecord<typeof Order>;
|
|
42
|
+
// {
|
|
43
|
+
// id: string; number: number; status: 'pending' | 'paid' | 'shipped'; customer: string;
|
|
44
|
+
// tags: string[]; items?: { sku: string; qty?: number }[];
|
|
45
|
+
// shipping?: { city: string; zip?: string }; createdAt: Date; updatedAt: Date;
|
|
46
|
+
// }
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### Inferred types
|
|
50
|
+
|
|
51
|
+
No interface to write or keep in step: `defineModel` reads the schema literal.
|
|
52
|
+
|
|
53
|
+
| Schema | Record type (`InferRecord<typeof M>`) | `create()` input (`InferCreate<typeof M>`) |
|
|
54
|
+
|---|---|---|
|
|
55
|
+
| `'string'` / `'number'` / `'boolean'` | `string` / `number` / `boolean` | same |
|
|
56
|
+
| `'date'` | `Date` (also inside embedded objects/arrays, on both engines) | `Date \| string \| number` |
|
|
57
|
+
| `'objectId'` | `string` | `string` |
|
|
58
|
+
| `enum: [...]` | union of the literals | same |
|
|
59
|
+
| `{ type: 'array', of }`, `[schema]` | `X[]` | `X[]` |
|
|
60
|
+
| nested schema / `{ type: 'object', fields }` | object, inferred recursively | same, with create rules |
|
|
61
|
+
| `{ type: 'object' }` / `{ type: 'array' }` without `of`/`fields` | `unknown` / `unknown[]` | same |
|
|
62
|
+
| `required`, `default` or `sequence` | non-optional | mandatory only if `required` without `default`/`sequence` |
|
|
63
|
+
| anything else | optional (`?`) | optional |
|
|
64
|
+
|
|
65
|
+
Timestamps follow `options.timestamps` (`createdAt`/`updatedAt: Date`, renamed or left out). Filters, updates, `distinct()` fields and return values are all typed from the record; an undeclared field or a value outside an `enum` is a compile error.
|
|
66
|
+
|
|
67
|
+
The explicit form still works and keeps the v0.4 behaviour (`create()` takes `Partial<T>`):
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
interface Legacy { title: string; pages?: number }
|
|
71
|
+
const Book = defineModel<Legacy>('Book', { title: { type: 'string' }, pages: { type: 'number' } });
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
A schema stored in a variable annotated as `ModelSchema` has nothing to infer from — declare it inline (or `as const satisfies ModelSchema`) to get the types.
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
|
|
78
|
+
## Schema fields
|
|
79
|
+
|
|
80
|
+
A field is one of:
|
|
81
|
+
|
|
82
|
+
| Form | Example | Meaning |
|
|
83
|
+
|---|---|---|
|
|
84
|
+
| `FieldDefinition` | `{ type: 'string', required: true }` | A typed field |
|
|
85
|
+
| Nested schema (shorthand) | `shipping: { city: { type: 'string' } }` | Embedded object with typed, validated fields |
|
|
86
|
+
| `{ type: 'object', fields }` | `{ type: 'object', required: true, fields: { … } }` | Embedded object that can itself be `required` |
|
|
87
|
+
| `[schema]` | `items: [{ sku: { type: 'string' } }]` | Array of embedded documents |
|
|
88
|
+
| `{ type: 'array', of }` | `{ type: 'array', of: 'string' }` / `of: { … }` | Typed array of primitives or embedded documents |
|
|
89
|
+
|
|
90
|
+
Inner `required` fields of an embedded object only apply when the object is present.
|
|
91
|
+
|
|
92
|
+
### `FieldDefinition`
|
|
93
|
+
|
|
94
|
+
| Option | Applies to | Description |
|
|
95
|
+
|---|---|---|
|
|
96
|
+
| `type` | all | `'string' \| 'number' \| 'boolean' \| 'date' \| 'objectId' \| 'object' \| 'array'` |
|
|
97
|
+
| `required` | all | Rejects missing (and explicitly `null`) values |
|
|
98
|
+
| `unique` | all | Unique index; duplicates throw `HttpError(409)` |
|
|
99
|
+
| `index` | all | Single-field index |
|
|
100
|
+
| `default` | all | Literal, function, or an operator code (below) |
|
|
101
|
+
| `enum` | string, number | Allowed values |
|
|
102
|
+
| `min` / `max` | number, date | Inclusive bounds |
|
|
103
|
+
| `minLength` / `maxLength` | string | Inclusive length bounds |
|
|
104
|
+
| `match` | string | `RegExp` the value must match |
|
|
105
|
+
| `validate` | all | `(value) => true \| false \| 'message'` — may be async |
|
|
106
|
+
| `ref` | objectId, objectId arrays | Model name, enables `populate` |
|
|
107
|
+
| `of` | array | Item type: a primitive name or a nested schema |
|
|
108
|
+
| `fields` | object | Typed fields of an embedded object |
|
|
109
|
+
| `sequence` | number | Auto-increment (below) |
|
|
110
|
+
|
|
111
|
+
`type: 'object'` without `fields` (and `array` without `of`) store any JSON value unvalidated.
|
|
112
|
+
|
|
113
|
+
**Types per engine.** `objectId` is a mongoose `ObjectId` on MongoDB and a `uuid` on PostgreSQL (ids are UUIDs there). On PostgreSQL, embedded objects and arrays are `jsonb` columns, `date` is `timestamptz`, `number` is `double precision` (`bigint` for sequences).
|
|
114
|
+
|
|
115
|
+
### Default operator codes
|
|
116
|
+
|
|
117
|
+
| Code | Resolves to (per record) | Pair with |
|
|
118
|
+
|---|---|---|
|
|
119
|
+
| `'$now'` | `new Date()` | `date` |
|
|
120
|
+
| `'$uuid'` | `crypto.randomUUID()` | `string` |
|
|
121
|
+
| `'$objectId'` | a fresh id (ObjectId / UUID) | `objectId` |
|
|
122
|
+
| `'$timestamp'` | `Date.now()` | `number` |
|
|
123
|
+
| `'$shortId'` | 16-char base64url string | `string` |
|
|
124
|
+
| `'$currentUser'` | the request's JWT payload (`getCurrentUser()`) | `object` |
|
|
125
|
+
| `'$currentUser.<key>'` | one field of it, e.g. `'$currentUser.id'` | that field's type |
|
|
126
|
+
|
|
127
|
+
`$currentUser` codes resolve to `undefined` outside a request or without `requireAuth` — they never throw. Any other value is used literally.
|
|
128
|
+
|
|
129
|
+
### Sequence fields
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
orderNumber: { type: 'number', sequence: true, required: true }
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
`sequence: true` keys the counter `'<Model>.<field>'`; a string shares one counter across fields/models. Values are assigned on insert, before `required` runs, and only when not supplied. MongoDB keeps counters in `efc_counters` (atomic `$inc` + upsert); PostgreSQL uses a real `SEQUENCE` (`efc_seq_<key>`). Top-level fields only.
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## `ModelOptions`
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
interface ModelOptions {
|
|
143
|
+
timestamps?: boolean | { createdAt?: string | false; updatedAt?: string | false }; // default true
|
|
144
|
+
indexes?: IndexDefinition[];
|
|
145
|
+
collection?: string; // collection (MongoDB) or table (PostgreSQL) name
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
interface IndexDefinition {
|
|
149
|
+
fields: Record<string, 1 | -1 | 'text'>;
|
|
150
|
+
unique?: boolean;
|
|
151
|
+
expireAfterSeconds?: number; // MongoDB TTL index only
|
|
152
|
+
name?: string;
|
|
153
|
+
}
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Indexes (including `unique`/`index` field options) are created by [`Model.sync()`](#syncmigrations) — automatically on first use unless `autoSync: false`. Text indexes use MongoDB text search or a PostgreSQL GIN `to_tsvector('simple', …)` index; TTL indexes are MongoDB-only and `sync()` rejects them on PostgreSQL.
|
|
157
|
+
|
|
158
|
+
---
|
|
159
|
+
|
|
160
|
+
## `ModelCRUD<T>`
|
|
161
|
+
|
|
162
|
+
Every record has a string `id` (MongoDB records also keep `_id`). Unset fields are absent from records on both engines.
|
|
163
|
+
|
|
164
|
+
### Reading
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
find(filter?: Filter<T>, options?: FindOptions): Promise<ModelRecord<T>[]>
|
|
168
|
+
findOne(filter: Filter<T>, options?: ModelQueryOptions): Promise<ModelRecord<T> | null>
|
|
169
|
+
findById(id: string, options?: ModelQueryOptions): Promise<ModelRecord<T> | null>
|
|
170
|
+
count(filter?: Filter<T>): Promise<number>
|
|
171
|
+
exists(filter: Filter<T>): Promise<boolean>
|
|
172
|
+
distinct(field: ScalarKeys<T>, filter?: Filter<T>): Promise<T[field][]>
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`distinct()` returns the non-null values of a scalar field (or `id`, `createdAt`, …) among matching records, de-duplicated and sorted ascending. Array and object fields are rejected — the two engines disagree on what "distinct" means for them.
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
interface FindOptions {
|
|
179
|
+
populate?: string | string[]; // resolve `ref` fields into records
|
|
180
|
+
select?: string[]; // only these fields (id always included)
|
|
181
|
+
sort?: Record<string, 1 | -1 | 'asc' | 'desc'>;
|
|
182
|
+
limit?: number;
|
|
183
|
+
skip?: number;
|
|
184
|
+
}
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
const page = await Order.find(
|
|
189
|
+
{ status: { $in: ['paid', 'shipped'] }, 'shipping.city': 'Oslo' },
|
|
190
|
+
{ sort: { createdAt: -1 }, skip: 20, limit: 20, select: ['number', 'status'], populate: 'customer' },
|
|
191
|
+
);
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
`findById` with a malformed id returns `null`, like an unknown one.
|
|
195
|
+
|
|
196
|
+
### Filters
|
|
197
|
+
|
|
198
|
+
| Filter | Matches |
|
|
199
|
+
|---|---|
|
|
200
|
+
| `{ status: 'paid' }` | equality (`null` matches missing/null) |
|
|
201
|
+
| `{ tags: 'sale' }` | array field **contains** the value |
|
|
202
|
+
| `{ total: { $gte: 10, $lt: 100 } }` | `$eq $ne $gt $gte $lt $lte` |
|
|
203
|
+
| `{ status: { $in: [...] } }` | `$in`, `$nin` |
|
|
204
|
+
| `{ coupon: { $exists: false } }` | field present / absent |
|
|
205
|
+
| `{ title: { $regex: /^intro/i } }` | regular expression |
|
|
206
|
+
| `{ 'shipping.city': 'Oslo' }` | dotted path into an embedded object |
|
|
207
|
+
| `{ $or: [{…}, {…}] }`, `$and` | combinations |
|
|
208
|
+
| `{ id: { $in: ids } }` | primary key |
|
|
209
|
+
|
|
210
|
+
This subset behaves identically on both engines and is typed (`Filter<T>`) — no casts needed. Other MongoDB operators pass through on MongoDB and are rejected with a `ModelValidationError` on PostgreSQL.
|
|
211
|
+
|
|
212
|
+
### Writing
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
create(data: CreateInput): Promise<ModelRecord<T>>
|
|
216
|
+
createMany(data: CreateInput[]): Promise<ModelRecord<T>[]>
|
|
217
|
+
update(id: string, data: Update<T>): Promise<ModelRecord<T> | null> // returns the updated record
|
|
218
|
+
updateOne(filter: Filter<T>, data: Update<T>): Promise<ModelRecord<T> | null>
|
|
219
|
+
updateMany(filter: Filter<T>, data: Update<T>): Promise<number> // records modified
|
|
220
|
+
upsert(filter: Filter<T>, create: CreateInput, update: Update<T>): Promise<ModelRecord<T>>
|
|
221
|
+
delete(id: string): Promise<void>
|
|
222
|
+
deleteOne(filter: Filter<T>): Promise<ModelRecord<T> | null> // returns the deleted record
|
|
223
|
+
deleteMany(filter: Filter<T>): Promise<number> // records deleted
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
- `updateOne` / `deleteOne` act on the first matching record in **one statement** (`findOneAndUpdate` / `UPDATE … WHERE id = (SELECT … LIMIT 1 FOR UPDATE)`) and return it, or `null` if nothing matched. Which record is "first" is unspecified when several match.
|
|
227
|
+
- `upsert` applies `update` to the first match, or creates `create` if there is none, and returns the record. `create` is used as given — `filter` fields are not copied into it. Put a `unique` index on the filtered field(s) to make concurrent upserts safe: a duplicate on create (409) is retried once as an update.
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
await Order.upsert({ number: 42 }, { number: 42, customer }, { $set: { status: 'paid' } });
|
|
231
|
+
const next = await Order.updateOne({ status: 'pending' }, { status: 'paid' });
|
|
232
|
+
const statuses = await Order.distinct('status', { customer }); // ('pending' | 'paid' | 'shipped')[]
|
|
233
|
+
if (await Order.exists({ customer, status: 'pending' })) { /* … */ }
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
`Update<T>` is plain fields (shorthand for `$set`) and/or operators:
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
await Order.update(id, { status: 'paid' });
|
|
240
|
+
await Order.update(id, {
|
|
241
|
+
$set: { 'shipping.zip': '01234' },
|
|
242
|
+
$inc: { attempts: 1 },
|
|
243
|
+
$push: { tags: 'priority' }, // or { $each: ['a', 'b'] }
|
|
244
|
+
$pull: { tags: 'draft' },
|
|
245
|
+
$unset: { coupon: true },
|
|
246
|
+
});
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
**Updates are validated**: changed fields must satisfy their type, `enum`, bounds, `match` and custom `validate`, and a `required` field can't be unset or nulled. `updatedAt` is refreshed.
|
|
250
|
+
|
|
251
|
+
### Engine-specific
|
|
252
|
+
|
|
253
|
+
```ts
|
|
254
|
+
aggregate<R>(pipeline: object[]): Promise<R[]> // MongoDB only — rejects on PostgreSQL
|
|
255
|
+
raw(): Promise<unknown> // mongoose Model / Drizzle pgTable
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
`raw()` hands you the native object for anything the shared surface doesn't cover — e.g. Drizzle joins on PostgreSQL:
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
import { drizzle } from 'drizzle-orm/node-postgres';
|
|
262
|
+
import { eq } from 'drizzle-orm';
|
|
263
|
+
import { getDbClient } from 'express-file-cluster';
|
|
264
|
+
import type { Pool } from 'pg';
|
|
265
|
+
|
|
266
|
+
const orm = drizzle(getDbClient() as unknown as Pool); // the real pool, not the `db` proxy
|
|
267
|
+
const orders = (await Order.raw()) as any;
|
|
268
|
+
const customers = (await Customer.raw()) as any;
|
|
269
|
+
const rows = await orm.select().from(orders).innerJoin(customers, eq(orders.customer, customers.id));
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
### `sync()` / `drop()` {#syncmigrations}
|
|
273
|
+
|
|
274
|
+
```ts
|
|
275
|
+
sync(options?: { dryRun?: boolean }): Promise<string[]>
|
|
276
|
+
drop(): Promise<void> // drop the collection/table and its data
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
`sync()` reconciles the database with the model and returns the changes it made — with `dryRun`, the changes it *would* make, applying nothing. On PostgreSQL those are SQL statements, run in one transaction under an advisory lock (concurrent syncs from several workers are safe): create the table, add columns, convert changed column types, drop stale `NOT NULL`s, rebuild enum checks, create declared indexes and drop EFC-created ones the model no longer declares. It never drops a column or a row. On MongoDB it creates the collection and syncs indexes.
|
|
280
|
+
|
|
281
|
+
It runs automatically the first time a model is used in a process (`autoSync`, default on). Call it yourself from [migrations](../guides/migrations.md), or use `efc db sync [--dry-run]` for every model in `src/model(s)/`.
|
|
282
|
+
|
|
283
|
+
### Undeclared fields
|
|
284
|
+
|
|
285
|
+
Same on both engines (mongoose's defaults): ignored on `create`/`update`, treated as absent in filters — `{ x: null }`, `{ x: { $exists: false } }`, `{ x: { $ne: … } }` match every record, other conditions match none — and ignored in `sort` and `select`.
|
|
286
|
+
|
|
287
|
+
---
|
|
288
|
+
|
|
289
|
+
## Errors
|
|
290
|
+
|
|
291
|
+
| Situation | Thrown | HTTP (via the global handler) |
|
|
292
|
+
|---|---|---|
|
|
293
|
+
| Validation failure (create/update) | `ModelValidationError` | `400` with `issues: [{ path, message }]` |
|
|
294
|
+
| Duplicate value of a `unique` field | `HttpError` | `409` — `"Order with this number already exists"` |
|
|
295
|
+
| Unsupported operator (PostgreSQL) | `ModelValidationError` | `400` |
|
|
296
|
+
| Table missing with `autoSync: false` (PostgreSQL) | `Error` naming the table | `500` |
|
|
297
|
+
|
|
298
|
+
```ts
|
|
299
|
+
import { ModelValidationError } from 'express-file-cluster';
|
|
300
|
+
|
|
301
|
+
try {
|
|
302
|
+
await User.create(input);
|
|
303
|
+
} catch (err) {
|
|
304
|
+
if (err instanceof ModelValidationError) console.log(err.issues); // [{ path: 'email', message: 'is required' }]
|
|
305
|
+
throw err;
|
|
306
|
+
}
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
---
|
|
310
|
+
|
|
311
|
+
## `transaction(fn)`
|
|
312
|
+
|
|
313
|
+
```ts
|
|
314
|
+
function transaction<T>(fn: () => Promise<T>): Promise<T>
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
Every model call inside `fn` — however deeply nested — joins the transaction automatically; a throw rolls everything back. Nested calls reuse the outer transaction.
|
|
318
|
+
|
|
319
|
+
```ts
|
|
320
|
+
import { transaction } from 'express-file-cluster';
|
|
321
|
+
|
|
322
|
+
await transaction(async () => {
|
|
323
|
+
const order = await Order.create({ customer: customerId, items });
|
|
324
|
+
await Stock.updateMany({ sku: { $in: items.map((i) => i.sku) } }, { $inc: { count: -1 } });
|
|
325
|
+
return order;
|
|
326
|
+
});
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
MongoDB transactions require a replica set (Atlas, or `mongod --replSet`).
|
|
330
|
+
|
|
331
|
+
---
|
|
332
|
+
|
|
333
|
+
## `db` — native client
|
|
334
|
+
|
|
335
|
+
`db` forwards to the live client from Pre-Flight: a mongoose `Connection` on MongoDB, a node-postgres `Pool` on PostgreSQL.
|
|
336
|
+
|
|
337
|
+
```ts
|
|
338
|
+
import { db } from 'express-file-cluster';
|
|
339
|
+
|
|
340
|
+
// MongoDB
|
|
341
|
+
const stats = await db.model('User').aggregate([{ $group: { _id: '$role', n: { $sum: 1 } } }]);
|
|
342
|
+
|
|
343
|
+
// PostgreSQL
|
|
344
|
+
const { rows } = await db.query('SELECT role, count(*) FROM users GROUP BY role');
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
It throws if accessed before Pre-Flight completes (e.g. at module load time) — use it inside handlers, tasks and migrations.
|
|
348
|
+
|
|
349
|
+
### `getDbClient()` / `setDbClient()`
|
|
350
|
+
|
|
351
|
+
Read or replace the client behind `db` — mainly for tests that bypass `ignite()`.
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# `HttpError` — API Reference
|
|
2
|
+
|
|
3
|
+
`HttpError` is EFC's built-in exception class for signalling HTTP error responses from route handlers. Throw it anywhere in a handler and the global error interceptor will format the response automatically.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { HttpError } from 'express-file-cluster';
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Constructor
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
new HttpError(statusCode: number, message: string)
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
| Parameter | Type | Description |
|
|
18
|
+
|---|---|---|
|
|
19
|
+
| `statusCode` | `number` | HTTP status code (e.g. `400`, `401`, `403`, `404`, `422`, `500`) |
|
|
20
|
+
| `message` | `string` | Human-readable error message included in the response body |
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## Properties
|
|
25
|
+
|
|
26
|
+
| Property | Type | Description |
|
|
27
|
+
|---|---|---|
|
|
28
|
+
| `statusCode` | `number` | The HTTP status code passed to the constructor |
|
|
29
|
+
| `message` | `string` | Inherited from `Error` — the message passed to the constructor |
|
|
30
|
+
| `name` | `string` | Always `'HttpError'` |
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## Usage
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
// src/api/users/[id].ts
|
|
38
|
+
import type { Request, Response } from 'express';
|
|
39
|
+
import { HttpError } from 'express-file-cluster';
|
|
40
|
+
import { User } from '../../model/User.js';
|
|
41
|
+
|
|
42
|
+
export const GET = async (req: Request, res: Response) => {
|
|
43
|
+
const user = await User.findById(req.params.id);
|
|
44
|
+
if (!user) throw new HttpError(404, 'User not found');
|
|
45
|
+
res.json(user);
|
|
46
|
+
};
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The global error interceptor catches the throw and responds with:
|
|
50
|
+
|
|
51
|
+
```json
|
|
52
|
+
{
|
|
53
|
+
"error": "User not found",
|
|
54
|
+
"statusCode": 404
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## Default response shape
|
|
61
|
+
|
|
62
|
+
When `HttpError` is thrown and no custom `onError` handler is configured:
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
HTTP/1.1 404 Not Found
|
|
66
|
+
Content-Type: application/json
|
|
67
|
+
|
|
68
|
+
{
|
|
69
|
+
"error": "User not found",
|
|
70
|
+
"statusCode": 404
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## Overriding the error handler
|
|
77
|
+
|
|
78
|
+
If you provide `onError` in `ignite()`, you receive the raw `HttpError` and can format the response however you want:
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
ignite({
|
|
82
|
+
onError: (err, req, res, _next) => {
|
|
83
|
+
if (err instanceof HttpError) {
|
|
84
|
+
res.status(err.statusCode).json({
|
|
85
|
+
code: err.statusCode,
|
|
86
|
+
message: err.message,
|
|
87
|
+
path: req.path,
|
|
88
|
+
});
|
|
89
|
+
} else {
|
|
90
|
+
res.status(500).json({ code: 500, message: 'Internal Server Error' });
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## Non-`HttpError` exceptions
|
|
99
|
+
|
|
100
|
+
Any `throw` that is *not* an `HttpError` (or a subclass) is treated as an unexpected server error:
|
|
101
|
+
|
|
102
|
+
```json
|
|
103
|
+
{
|
|
104
|
+
"error": "Internal Server Error",
|
|
105
|
+
"statusCode": 500
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
The original error is logged to `stderr` with `[EFC] Unhandled error:`.
|