express-file-cluster 0.7.1 → 0.9.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 +3 -1
- package/dist/auth/index.cjs +3 -3
- package/dist/auth/index.d.cts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +2 -2
- package/dist/{chunk-ZDM5JHVK.cjs → chunk-2J3HHQKP.cjs} +3 -3
- package/dist/{chunk-ZDM5JHVK.cjs.map → chunk-2J3HHQKP.cjs.map} +1 -1
- package/dist/chunk-2PBMLMO4.js +1386 -0
- package/dist/chunk-2PBMLMO4.js.map +1 -0
- package/dist/chunk-66R7S7J3.cjs +1386 -0
- package/dist/chunk-66R7S7J3.cjs.map +1 -0
- package/dist/{chunk-6OGOVV57.js → chunk-6QNLN6AI.js} +118 -1266
- package/dist/chunk-6QNLN6AI.js.map +1 -0
- package/dist/chunk-BBSZLGZW.js +113 -0
- package/dist/chunk-BBSZLGZW.js.map +1 -0
- package/dist/{chunk-BUBXO7WU.js → chunk-HXV543HZ.js} +10 -3
- package/dist/chunk-HXV543HZ.js.map +1 -0
- package/dist/chunk-QL6EWT4B.cjs +113 -0
- package/dist/chunk-QL6EWT4B.cjs.map +1 -0
- package/dist/{chunk-AZYXQU3Z.cjs → chunk-RGTENTDN.cjs} +239 -1387
- package/dist/chunk-RGTENTDN.cjs.map +1 -0
- package/dist/{chunk-TRC4DUZB.js → chunk-RSZB7VAO.js} +2 -2
- package/dist/{chunk-MGH4VDV3.cjs → chunk-VQSWSYK6.cjs} +10 -3
- package/dist/chunk-VQSWSYK6.cjs.map +1 -0
- package/dist/cli/db-runner.cjs +613 -28
- package/dist/cli/db-runner.cjs.map +1 -1
- package/dist/cli/db-runner.js +611 -26
- package/dist/cli/db-runner.js.map +1 -1
- package/dist/cli/index.cjs +1210 -12
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +1221 -23
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/db.md +1 -0
- package/dist/docs/api-reference/ignite.md +19 -0
- package/dist/docs/api-reference/table.md +3 -0
- package/dist/docs/cli/add.md +136 -0
- package/dist/docs/cli/db.md +25 -2
- package/dist/docs/cli/index.md +10 -1
- package/dist/docs/core-concepts/middleware.md +1 -1
- package/dist/docs/getting-started/index.md +25 -18
- package/dist/docs/getting-started/project-structure.md +6 -7
- package/dist/docs/guides/authentication.md +3 -1
- package/dist/docs/guides/coming-from-prisma.md +75 -0
- package/dist/docs/guides/database.md +5 -2
- package/dist/docs/guides/generated-portals.md +36 -19
- package/dist/docs/guides/mailer.md +7 -10
- package/dist/docs/guides/migrations.md +114 -3
- package/dist/docs/guides/oauth.md +94 -0
- package/dist/docs/guides/rbac.md +5 -40
- package/dist/docs/guides/relations.md +147 -0
- package/dist/docs/guides/which-api.md +50 -0
- package/dist/docs/index.md +7 -3
- package/dist/docs/skills/SKILL.md +3 -3
- package/dist/docs/skills/api-surface.md +1 -0
- package/dist/docs/skills/what-not-to-invent.md +22 -6
- package/dist/index.cjs +20 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +12 -10
- package/dist/index.js.map +1 -1
- package/dist/registry/index.json +506 -0
- package/dist/registry/js-mongo/_base.json +1 -0
- package/dist/registry/js-mongo/account-security.json +1 -0
- package/dist/registry/js-mongo/account-settings.json +1 -0
- package/dist/registry/js-mongo/admin-admins.json +1 -0
- package/dist/registry/js-mongo/admin-analytics.json +1 -0
- package/dist/registry/js-mongo/admin-billing.json +1 -0
- package/dist/registry/js-mongo/admin-content.json +1 -0
- package/dist/registry/js-mongo/admin-logs.json +1 -0
- package/dist/registry/js-mongo/admin-support.json +1 -0
- package/dist/registry/js-mongo/admin-system.json +1 -0
- package/dist/registry/js-mongo/admin-users.json +1 -0
- package/dist/registry/js-mongo/admin.json +1 -0
- package/dist/registry/js-mongo/auth.json +1 -0
- package/dist/registry/js-mongo/auth@apple.json +1 -0
- package/dist/registry/js-mongo/auth@google.json +1 -0
- package/dist/registry/js-mongo/billing.json +1 -0
- package/dist/registry/js-mongo/email-client.json +1 -0
- package/dist/registry/js-mongo/email-verification.json +1 -0
- package/dist/registry/js-mongo/files.json +1 -0
- package/dist/registry/js-mongo/forgot-password.json +1 -0
- package/dist/registry/js-mongo/notifications.json +1 -0
- package/dist/registry/js-mongo/support.json +1 -0
- package/dist/registry/js-mongo/user-profile.json +1 -0
- package/dist/registry/js-pg-model/_base.json +1 -0
- package/dist/registry/js-pg-model/account-security.json +1 -0
- package/dist/registry/js-pg-model/account-settings.json +1 -0
- package/dist/registry/js-pg-model/admin-admins.json +1 -0
- package/dist/registry/js-pg-model/admin-analytics.json +1 -0
- package/dist/registry/js-pg-model/admin-billing.json +1 -0
- package/dist/registry/js-pg-model/admin-content.json +1 -0
- package/dist/registry/js-pg-model/admin-logs.json +1 -0
- package/dist/registry/js-pg-model/admin-support.json +1 -0
- package/dist/registry/js-pg-model/admin-system.json +1 -0
- package/dist/registry/js-pg-model/admin-users.json +1 -0
- package/dist/registry/js-pg-model/admin.json +1 -0
- package/dist/registry/js-pg-model/auth.json +1 -0
- package/dist/registry/js-pg-model/auth@apple.json +1 -0
- package/dist/registry/js-pg-model/auth@google.json +1 -0
- package/dist/registry/js-pg-model/billing.json +1 -0
- package/dist/registry/js-pg-model/email-client.json +1 -0
- package/dist/registry/js-pg-model/email-verification.json +1 -0
- package/dist/registry/js-pg-model/files.json +1 -0
- package/dist/registry/js-pg-model/forgot-password.json +1 -0
- package/dist/registry/js-pg-model/notifications.json +1 -0
- package/dist/registry/js-pg-model/support.json +1 -0
- package/dist/registry/js-pg-model/user-profile.json +1 -0
- package/dist/registry/js-pg-table/_base.json +1 -0
- package/dist/registry/js-pg-table/account-security.json +1 -0
- package/dist/registry/js-pg-table/account-settings.json +1 -0
- package/dist/registry/js-pg-table/admin-admins.json +1 -0
- package/dist/registry/js-pg-table/admin-analytics.json +1 -0
- package/dist/registry/js-pg-table/admin-billing.json +1 -0
- package/dist/registry/js-pg-table/admin-content.json +1 -0
- package/dist/registry/js-pg-table/admin-logs.json +1 -0
- package/dist/registry/js-pg-table/admin-support.json +1 -0
- package/dist/registry/js-pg-table/admin-system.json +1 -0
- package/dist/registry/js-pg-table/admin-users.json +1 -0
- package/dist/registry/js-pg-table/admin.json +1 -0
- package/dist/registry/js-pg-table/auth.json +1 -0
- package/dist/registry/js-pg-table/auth@apple.json +1 -0
- package/dist/registry/js-pg-table/auth@google.json +1 -0
- package/dist/registry/js-pg-table/billing.json +1 -0
- package/dist/registry/js-pg-table/email-client.json +1 -0
- package/dist/registry/js-pg-table/email-verification.json +1 -0
- package/dist/registry/js-pg-table/files.json +1 -0
- package/dist/registry/js-pg-table/forgot-password.json +1 -0
- package/dist/registry/js-pg-table/notifications.json +1 -0
- package/dist/registry/js-pg-table/support.json +1 -0
- package/dist/registry/js-pg-table/user-profile.json +1 -0
- package/dist/registry/ts-mongo/_base.json +1 -0
- package/dist/registry/ts-mongo/account-security.json +1 -0
- package/dist/registry/ts-mongo/account-settings.json +1 -0
- package/dist/registry/ts-mongo/admin-admins.json +1 -0
- package/dist/registry/ts-mongo/admin-analytics.json +1 -0
- package/dist/registry/ts-mongo/admin-billing.json +1 -0
- package/dist/registry/ts-mongo/admin-content.json +1 -0
- package/dist/registry/ts-mongo/admin-logs.json +1 -0
- package/dist/registry/ts-mongo/admin-support.json +1 -0
- package/dist/registry/ts-mongo/admin-system.json +1 -0
- package/dist/registry/ts-mongo/admin-users.json +1 -0
- package/dist/registry/ts-mongo/admin.json +1 -0
- package/dist/registry/ts-mongo/auth.json +1 -0
- package/dist/registry/ts-mongo/auth@apple.json +1 -0
- package/dist/registry/ts-mongo/auth@google.json +1 -0
- package/dist/registry/ts-mongo/billing.json +1 -0
- package/dist/registry/ts-mongo/email-client.json +1 -0
- package/dist/registry/ts-mongo/email-verification.json +1 -0
- package/dist/registry/ts-mongo/files.json +1 -0
- package/dist/registry/ts-mongo/forgot-password.json +1 -0
- package/dist/registry/ts-mongo/notifications.json +1 -0
- package/dist/registry/ts-mongo/support.json +1 -0
- package/dist/registry/ts-mongo/user-profile.json +1 -0
- package/dist/registry/ts-pg-model/_base.json +1 -0
- package/dist/registry/ts-pg-model/account-security.json +1 -0
- package/dist/registry/ts-pg-model/account-settings.json +1 -0
- package/dist/registry/ts-pg-model/admin-admins.json +1 -0
- package/dist/registry/ts-pg-model/admin-analytics.json +1 -0
- package/dist/registry/ts-pg-model/admin-billing.json +1 -0
- package/dist/registry/ts-pg-model/admin-content.json +1 -0
- package/dist/registry/ts-pg-model/admin-logs.json +1 -0
- package/dist/registry/ts-pg-model/admin-support.json +1 -0
- package/dist/registry/ts-pg-model/admin-system.json +1 -0
- package/dist/registry/ts-pg-model/admin-users.json +1 -0
- package/dist/registry/ts-pg-model/admin.json +1 -0
- package/dist/registry/ts-pg-model/auth.json +1 -0
- package/dist/registry/ts-pg-model/auth@apple.json +1 -0
- package/dist/registry/ts-pg-model/auth@google.json +1 -0
- package/dist/registry/ts-pg-model/billing.json +1 -0
- package/dist/registry/ts-pg-model/email-client.json +1 -0
- package/dist/registry/ts-pg-model/email-verification.json +1 -0
- package/dist/registry/ts-pg-model/files.json +1 -0
- package/dist/registry/ts-pg-model/forgot-password.json +1 -0
- package/dist/registry/ts-pg-model/notifications.json +1 -0
- package/dist/registry/ts-pg-model/support.json +1 -0
- package/dist/registry/ts-pg-model/user-profile.json +1 -0
- package/dist/registry/ts-pg-table/_base.json +1 -0
- package/dist/registry/ts-pg-table/account-security.json +1 -0
- package/dist/registry/ts-pg-table/account-settings.json +1 -0
- package/dist/registry/ts-pg-table/admin-admins.json +1 -0
- package/dist/registry/ts-pg-table/admin-analytics.json +1 -0
- package/dist/registry/ts-pg-table/admin-billing.json +1 -0
- package/dist/registry/ts-pg-table/admin-content.json +1 -0
- package/dist/registry/ts-pg-table/admin-logs.json +1 -0
- package/dist/registry/ts-pg-table/admin-support.json +1 -0
- package/dist/registry/ts-pg-table/admin-system.json +1 -0
- package/dist/registry/ts-pg-table/admin-users.json +1 -0
- package/dist/registry/ts-pg-table/admin.json +1 -0
- package/dist/registry/ts-pg-table/auth.json +1 -0
- package/dist/registry/ts-pg-table/auth@apple.json +1 -0
- package/dist/registry/ts-pg-table/auth@google.json +1 -0
- package/dist/registry/ts-pg-table/billing.json +1 -0
- package/dist/registry/ts-pg-table/email-client.json +1 -0
- package/dist/registry/ts-pg-table/email-verification.json +1 -0
- package/dist/registry/ts-pg-table/files.json +1 -0
- package/dist/registry/ts-pg-table/forgot-password.json +1 -0
- package/dist/registry/ts-pg-table/notifications.json +1 -0
- package/dist/registry/ts-pg-table/support.json +1 -0
- package/dist/registry/ts-pg-table/user-profile.json +1 -0
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/{types-B6lVw4bj.d.ts → types-gyvA7BtO.d.cts} +18 -1
- package/dist/{types-B6lVw4bj.d.cts → types-gyvA7BtO.d.ts} +18 -1
- package/package.json +11 -2
- package/dist/chunk-6OGOVV57.js.map +0 -1
- package/dist/chunk-AZYXQU3Z.cjs.map +0 -1
- package/dist/chunk-BUBXO7WU.js.map +0 -1
- package/dist/chunk-MGH4VDV3.cjs.map +0 -1
- /package/dist/{chunk-TRC4DUZB.js.map → chunk-RSZB7VAO.js.map} +0 -0
|
@@ -4,17 +4,128 @@
|
|
|
4
4
|
|
|
5
5
|
| Command | Does |
|
|
6
6
|
|---|---|
|
|
7
|
+
| `efc db generate <name>` | Writes a migration from the difference between your models and your migrations |
|
|
7
8
|
| `efc db migrate` | Runs pending migrations in `src/migrations/` as one new batch |
|
|
8
9
|
| `efc db rollback [--steps n]` | Reverts the last batch (or `n` batches), newest first |
|
|
9
10
|
| `efc db status` | Lists applied (with batch) and pending migrations |
|
|
10
11
|
| `efc db seed [name]` | Runs every seed in `src/seeds/`, or just one |
|
|
12
|
+
| `efc db sync [--dry-run] [--exit-code]` | Brings the database in line with the models (or reports what would change) |
|
|
13
|
+
| `efc db pull` | Writes `defineTable` models for an existing PostgreSQL database |
|
|
11
14
|
| `efc db studio [-p 4983]` | Opens a read-only database browser on `127.0.0.1` |
|
|
12
15
|
|
|
13
16
|
All of them read `DATABASE_URL` from the environment or `.env` (override with `--database-url`); the engine follows the URL scheme.
|
|
14
17
|
|
|
15
18
|
---
|
|
16
19
|
|
|
17
|
-
##
|
|
20
|
+
## Generating a migration from your models
|
|
21
|
+
|
|
22
|
+
Change a model, then let EFC write the migration:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
efc db generate add_post_views
|
|
26
|
+
# → src/migrations/20261023101500_add_post_views.ts
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`generate` replays your existing migrations into a **throwaway schema** (PostgreSQL) or database (MongoDB) on the same server, compares the result with the models in `src/model(s)/`, and writes the difference. Your development database isn't read or changed, so it doesn't matter that `autoSync` already brought it up to date. Run it without a name to just print the plan.
|
|
30
|
+
|
|
31
|
+
The file is ordinary code you own and should review:
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
// Generated by `efc db generate add_post_views` on 2026-10-23. Review it, then run `efc db migrate`.
|
|
35
|
+
import type { MigrationContext } from 'express-file-cluster';
|
|
36
|
+
|
|
37
|
+
export async function up({ db }: MigrationContext): Promise<void> {
|
|
38
|
+
await run(db, [
|
|
39
|
+
`ALTER TABLE "posts" ADD COLUMN IF NOT EXISTS "views" integer`,
|
|
40
|
+
`CREATE INDEX IF NOT EXISTS "posts_views_idx" ON "posts" ("views")`,
|
|
41
|
+
]);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function down({ db }: MigrationContext): Promise<void> {
|
|
45
|
+
await run(db, [
|
|
46
|
+
`DROP INDEX IF EXISTS "posts_views_idx"`,
|
|
47
|
+
`ALTER TABLE "posts" DROP COLUMN IF EXISTS "views"`,
|
|
48
|
+
]);
|
|
49
|
+
}
|
|
50
|
+
// …plus a small run() helper: one transaction, checks, and skip-if-applied guards
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
- **PostgreSQL:** the steps are SQL run in one transaction. Tables come first and foreign keys last, so models can reference each other in any order. Every statement is idempotent (`IF NOT EXISTS`, or guarded by a "skip if already applied" query), so running a migration over tables that already exist changes nothing.
|
|
54
|
+
- **MongoDB:** the steps create collections, build and drop indexes, and move renamed fields in stored documents.
|
|
55
|
+
- **`down()`** is a best-effort reverse. Anything without a safe inverse (a dropped column's data, an added enum value) is listed in a comment.
|
|
56
|
+
|
|
57
|
+
### What `generate` adds, and what it needs you to ask for
|
|
58
|
+
|
|
59
|
+
By default a migration contains what `sync` would do: create tables, columns, indexes, enum types and foreign keys, convert changed types, and relax `NOT NULL`s the model no longer asks for. Two kinds of change go further and need a flag:
|
|
60
|
+
|
|
61
|
+
| You want | Do | The migration |
|
|
62
|
+
|---|---|---|
|
|
63
|
+
| Rename a field and keep its data | `headline: { type: 'string', renamedFrom: 'title' }` | PostgreSQL: `RENAME COLUMN` (`sync` does this too). MongoDB: `$rename` in the stored documents |
|
|
64
|
+
| Drop columns the model no longer declares | `efc db generate <name> --allow-drop` | `DROP COLUMN` (the data is gone; `down()` re-adds an empty column) |
|
|
65
|
+
| Enforce `required` and `enum` in the database | `efc db generate <name> --tighten` | `SET NOT NULL` for required fields, `VALIDATE` for enum checks |
|
|
66
|
+
|
|
67
|
+
Tightening can fail on existing rows, so each step comes with a check that runs first. If anything would fail, the migration stops before changing anything, says how many rows are affected and what to fix, and the next `migrate` retries:
|
|
68
|
+
|
|
69
|
+
```
|
|
70
|
+
GenPost.headline is required, but 3 row(s) of "posts" have no value — fill them in, then run the migration again
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Foreign keys are validated in the migration the same way, after a count of rows that reference a missing record.
|
|
74
|
+
|
|
75
|
+
### Checking migrations against the models
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
efc db generate --verify
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
`--verify` replays every migration into a throwaway schema and fails (exit code 1) if the result is missing anything the models declare, listing the steps. Use it in CI so a model change can't ship without its migration. With a name, `generate <name> --verify` writes the migration and then verifies it.
|
|
82
|
+
|
|
83
|
+
### Drift: does the live database match?
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
efc db sync --dry-run --exit-code
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
This exits with code 2 when the database differs from the models (and 1 on an error). Run it against staging or production before a deploy.
|
|
90
|
+
|
|
91
|
+
### Starting migrations on an existing database
|
|
92
|
+
|
|
93
|
+
An app that has run on `autoSync` already has its tables. To start tracking migrations:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
efc db generate init # the whole current schema
|
|
97
|
+
efc db migrate --baseline # record it as applied, without running it
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`--baseline` records every pending migration as applied without running it. Because generated migrations are idempotent, running `init` instead also works: it skips what exists.
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## Pulling an existing database (PostgreSQL)
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
efc db pull # → src/model/<Model>.ts + index.ts
|
|
108
|
+
efc db pull --out pulled # somewhere else, to compare
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`pull` reads the current schema and writes `defineTable` models. It carries over:
|
|
112
|
+
|
|
113
|
+
- **Tables and ids:** each table with a single `id` primary key (uuid, integer or bigint) becomes a model. Integer and bigint ids become `id: 'serial'` and `'bigserial'`.
|
|
114
|
+
- **Columns and types:** varchar lengths, numeric precision, arrays and native enums. `NOT NULL` becomes `required: true`.
|
|
115
|
+
- **Defaults:** `now()`, `gen_random_uuid()`, literals and EFC sequences.
|
|
116
|
+
- **Naming:** `naming: 'snake_case'` when the columns follow it, plus `column` overrides and the table name.
|
|
117
|
+
- **Indexes:** unique, plain, compound and text indexes.
|
|
118
|
+
- **Relations:** foreign keys become `ref`s with `onDelete`. A column like `authorId` becomes an `author` field that keeps the `authorId` column. EFC join tables become many-to-many arrays, and every target model gets back-`relations`.
|
|
119
|
+
|
|
120
|
+
A schema EFC created pulls back to models that sync finds nothing to change in. For a schema EFC didn't create, anything that has no EFC equivalent is noted at the top of the file: expression or partial indexes, other CHECKs, composite keys, and other defaults. Existing files are kept unless you pass `--force`.
|
|
121
|
+
|
|
122
|
+
`required` and `default` live in the model, not the database. A table created by `sync` or a migration without `--tighten` has nullable columns and no defaults, so its fields pull back as optional. Generate with `--tighten` if you want `required` enforced (and pulled back).
|
|
123
|
+
|
|
124
|
+
Coming from Prisma? See [Coming from Prisma](./coming-from-prisma.md).
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## Writing a migration by hand
|
|
18
129
|
|
|
19
130
|
```bash
|
|
20
131
|
efc generate migration add_orders
|
|
@@ -39,7 +150,7 @@ export async function down({ db, engine }: MigrationContext): Promise<void> {
|
|
|
39
150
|
- `Model.sync()` reconciles the table/collection with the model (see [the schema takes care of itself](./database.md#the-schema-takes-care-of-itself)). It never drops a column or data, so it's safe to call from several migrations.
|
|
40
151
|
- `Model.drop()` removes the table/collection — for `down()`.
|
|
41
152
|
|
|
42
|
-
**Do I need migrations at all?** Not for schema shape: tables and indexes are reconciled automatically on first use. Use migrations for what sync deliberately won't do
|
|
153
|
+
**Do I need migrations at all?** Not for schema shape: tables and indexes are reconciled automatically on first use. Use migrations for what sync deliberately won't do, such as dropping columns, enforcing `NOT NULL`, splitting columns or backfilling data. If you run with `autoSync: false`, you need them for every schema change. `efc db generate` writes most of them for you. Projects created with `create-efc-app` include `src/migrations/00000000000000_init`, which syncs every generated model. Running it is optional. While `generate` replays migrations into its throwaway schema, `Model.sync()` calls inside them do nothing, because they'd mirror today's models and hide every change. So the first `efc db generate` in such an app captures the whole schema, and running it against your existing tables is harmless.
|
|
43
154
|
|
|
44
155
|
### `efc db sync`
|
|
45
156
|
|
|
@@ -48,7 +159,7 @@ efc db sync --dry-run # every model in src/model(s)/: what would change (SQL o
|
|
|
48
159
|
efc db sync # apply
|
|
49
160
|
```
|
|
50
161
|
|
|
51
|
-
Handy
|
|
162
|
+
Handy as the deploy step when `autoSync` is off. In CI, `--dry-run --exit-code` exits with code 2 when anything would change.
|
|
52
163
|
|
|
53
164
|
---
|
|
54
165
|
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# Sign in with Google & Apple
|
|
2
|
+
|
|
3
|
+
Two registry items add OAuth sign-in next to email/password [auth](./authentication.md):
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
efc add auth@google # asks for the Google client ID and secret
|
|
7
|
+
efc add auth@apple # asks for the Services ID, Team ID, Key ID and .p8 key
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Both install `auth` first if it's missing. Like every [registry item](../cli/add.md), the code is copied into your app and is yours to change. Nothing about it is hidden in a package.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## What gets added
|
|
15
|
+
|
|
16
|
+
| File | Purpose |
|
|
17
|
+
|---|---|
|
|
18
|
+
| `src/api/auth/google/index.ts` | `GET /auth/google`: redirects to Google's consent screen |
|
|
19
|
+
| `src/api/auth/google/callback.ts` | `GET /auth/google/callback`: Google redirects here, the user is signed in |
|
|
20
|
+
| `src/api/auth/apple/index.ts` | `GET /auth/apple`: redirects to Apple |
|
|
21
|
+
| `src/api/auth/apple/callback.ts` | `POST /auth/apple/callback`: Apple posts here (`form_post`), the user is signed in |
|
|
22
|
+
| `src/lib/oauth.ts` | Shared: the state cookie, find-or-create the user, issue the token |
|
|
23
|
+
| `src/model/OAuthAccount.ts` | Links a provider identity (`google:<sub>`) to a `User` |
|
|
24
|
+
|
|
25
|
+
Plus the `jose` package, which verifies the providers' ID tokens and signs Apple's client secret, and these env vars:
|
|
26
|
+
|
|
27
|
+
| Variable | |
|
|
28
|
+
|---|---|
|
|
29
|
+
| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | From your OAuth client in the Google Cloud console |
|
|
30
|
+
| `GOOGLE_REDIRECT_URI` | The callback URL, e.g. `http://localhost:3000/v1/api/auth/google/callback`. Register exactly this URL on the client |
|
|
31
|
+
| `APPLE_CLIENT_ID` | Your Services ID, e.g. `com.yourapp.signin` |
|
|
32
|
+
| `APPLE_TEAM_ID`, `APPLE_KEY_ID` | Your team ID and the ID of your Sign in with Apple key |
|
|
33
|
+
| `APPLE_PRIVATE_KEY` | The `.p8` key's contents, newlines written as `\n`. `efc add` reads the file for you |
|
|
34
|
+
| `APPLE_REDIRECT_URI` | The callback URL. It must be https, on a domain verified with Apple, and registered on the Services ID. Apple rejects `localhost` |
|
|
35
|
+
| `OAUTH_SUCCESS_REDIRECT` | Where the browser goes after signing in (your frontend) |
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## Setting up the providers
|
|
40
|
+
|
|
41
|
+
**Google.** In [console.cloud.google.com](https://console.cloud.google.com), go to *APIs & Services → Credentials → Create credentials → OAuth client ID*. Choose application type *Web application* and add `GOOGLE_REDIRECT_URI` under *Authorised redirect URIs*. Configure the consent screen if asked; the `openid`, `email` and `profile` scopes are enough.
|
|
42
|
+
|
|
43
|
+
**Apple.** In [developer.apple.com](https://developer.apple.com) → *Certificates, IDs & Profiles*:
|
|
44
|
+
|
|
45
|
+
1. An **App ID** with *Sign in with Apple* enabled.
|
|
46
|
+
2. A **Services ID** (this is `APPLE_CLIENT_ID`) with *Sign in with Apple* enabled, your domain, and `APPLE_REDIRECT_URI` as a return URL.
|
|
47
|
+
3. A **Key** with *Sign in with Apple*. Download the `.p8` file (you can only do this once) and note its Key ID.
|
|
48
|
+
|
|
49
|
+
To try Apple sign-in locally, expose your dev server over https with a tunnel and register that URL.
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## Using it from a frontend
|
|
54
|
+
|
|
55
|
+
Send the browser (not `fetch`) to the start route:
|
|
56
|
+
|
|
57
|
+
```html
|
|
58
|
+
<a href="https://api.yourapp.com/v1/api/auth/google">Continue with Google</a>
|
|
59
|
+
<a href="https://api.yourapp.com/v1/api/auth/apple">Continue with Apple</a>
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
After the provider sends the user back, the callback sets the usual `efc_token` cookie (the same one `/auth/login` sets) and redirects to `OAUTH_SUCCESS_REDIRECT`. From there, requests with credentials work as after a password login, and `GET /auth/me` returns the user.
|
|
63
|
+
|
|
64
|
+
> The callbacks issue the session as an http-only cookie, so they fit `authStrategy: 'http-only'`. With the `localStorage` (Bearer) strategy, change the callback to hand the token to your SPA, for example with `signToken()` and a redirect to your frontend that carries it.
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## How sign-in works
|
|
69
|
+
|
|
70
|
+
1. **Start.** The start route stores a random `state` and `nonce` (and, for Google, a PKCE verifier) in a short-lived http-only cookie, then redirects to the provider.
|
|
71
|
+
2. **Callback.** The callback checks `state` against the cookie and clears it. It trades the code for tokens at the provider (Google: with the PKCE verifier; Apple: with a client secret, an ES256 JWT signed with your key) and verifies the ID token's signature, issuer, audience and `nonce` against the provider's published keys.
|
|
72
|
+
3. **Find or create the user** (`signInWithOAuth` in `src/lib/oauth.ts`):
|
|
73
|
+
- the `User` already linked to this identity in `OAuthAccount`; otherwise
|
|
74
|
+
- the `User` with the same email, **if the provider says the email is verified**, which then gets linked; otherwise
|
|
75
|
+
- a new `User` (`isVerified: true`, a random password; they can set a real one with [forgot-password](./generated-portals.md)).
|
|
76
|
+
|
|
77
|
+
An unknown identity without a verified email is refused (400). A suspended user (`isActive: false`) gets 403.
|
|
78
|
+
4. **Sign in.** `issueToken()` sets the cookie and the browser goes to `OAUTH_SUCCESS_REDIRECT`.
|
|
79
|
+
|
|
80
|
+
Apple only sends the user's name on their **first** sign-in. The callback uses it when it creates the user.
|
|
81
|
+
|
|
82
|
+
Apple posts its callback from its own site, so the start route marks the Apple state cookie `SameSite=None; Secure`. Browsers accept that on https and on `localhost`.
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## Errors
|
|
87
|
+
|
|
88
|
+
| Status | When |
|
|
89
|
+
|---|---|
|
|
90
|
+
| 400 | The provider returned an error, the state is missing, expired (10 minutes) or doesn't match, the `nonce` doesn't match, or there's no verified email for a new identity |
|
|
91
|
+
| 403 | The user is suspended |
|
|
92
|
+
| 502 | The provider rejected the code exchange (wrong client secret / key, code already used, redirect URI mismatch) |
|
|
93
|
+
|
|
94
|
+
The callbacks answer with JSON errors. To send users back to your frontend instead, catch the error in the callback and redirect, e.g. to `${OAUTH_SUCCESS_REDIRECT}?error=…`.
|
package/dist/docs/guides/rbac.md
CHANGED
|
@@ -1,21 +1,6 @@
|
|
|
1
1
|
# Role-Based Access Control (RBAC)
|
|
2
2
|
|
|
3
|
-
Role checks are built into `requireAuth` itself — call it with role names (`requireAuth('admin')`) instead of a separate middleware (see [Authentication](./authentication.md)). `
|
|
4
|
-
|
|
5
|
-
---
|
|
6
|
-
|
|
7
|
-
## Enabling it
|
|
8
|
-
|
|
9
|
-
Toggle **Role-based access control** in the features multiselect:
|
|
10
|
-
|
|
11
|
-
```
|
|
12
|
-
? Features: (space to toggle, enter to confirm)
|
|
13
|
-
◉ User portal
|
|
14
|
-
◉ Admin portal
|
|
15
|
-
◉ Role-based access control
|
|
16
|
-
```
|
|
17
|
-
|
|
18
|
-
RBAC is most useful alongside **User portal** and/or **Admin portal**, since it changes how their generated routes are protected — but it can be toggled independently.
|
|
3
|
+
Role checks are built into `requireAuth` itself — call it with role names (`requireAuth('admin')`) instead of a separate middleware (see [Authentication](./authentication.md)). The routes the registry generates use it throughout, and the `admin-admins` item adds a `Role` model and a role-management API.
|
|
19
4
|
|
|
20
5
|
---
|
|
21
6
|
|
|
@@ -23,7 +8,7 @@ RBAC is most useful alongside **User portal** and/or **Admin portal**, since it
|
|
|
23
8
|
|
|
24
9
|
### Route protection
|
|
25
10
|
|
|
26
|
-
Every
|
|
11
|
+
Every protected route that [`efc add`](../cli/add.md) or `create-efc-app` generates checks roles with `requireAuth(...)`:
|
|
27
12
|
|
|
28
13
|
```ts
|
|
29
14
|
// User-facing routes
|
|
@@ -33,31 +18,11 @@ export const middlewares = [requireAuth('user', 'admin')];
|
|
|
33
18
|
export const middlewares = [requireAuth('admin')];
|
|
34
19
|
```
|
|
35
20
|
|
|
36
|
-
`requireAuth('admin')` verifies the JWT *and* checks that `payload.role` is one of the given roles
|
|
37
|
-
|
|
38
|
-
If RBAC is **not** enabled, admin routes fall back to an inline guard at the top of the handler instead:
|
|
39
|
-
|
|
40
|
-
```ts
|
|
41
|
-
export const middlewares = [requireAuth];
|
|
42
|
-
|
|
43
|
-
export const GET = async (req, res) => {
|
|
44
|
-
const user = (req as any).user;
|
|
45
|
-
if (user?.role !== 'admin') {
|
|
46
|
-
return res.status(403).json({ error: 'Forbidden: Admin access required' });
|
|
47
|
-
}
|
|
48
|
-
// ...
|
|
49
|
-
};
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
Both approaches produce the same 401/403 behavior — RBAC-on just centralizes the check into `requireAuth(...)` and adds the `Role` model below.
|
|
53
|
-
|
|
54
|
-
### `Role` model
|
|
55
|
-
|
|
56
|
-
A `src/model/Role.ts` model is created (`defineModel` on MongoDB, `defineTable` on PostgreSQL by default).
|
|
21
|
+
`requireAuth('admin')` verifies the JWT *and* checks that `payload.role` is one of the given roles. It returns `401` if the token is missing or invalid, and `403` if the role doesn't match.
|
|
57
22
|
|
|
58
|
-
###
|
|
23
|
+
### `Role` model and role management
|
|
59
24
|
|
|
60
|
-
|
|
25
|
+
`efc add admin-admins` creates `src/model/Role.ts` (`defineModel` on MongoDB, `defineTable` on PostgreSQL by default) and a role-management API:
|
|
61
26
|
|
|
62
27
|
| Method | Path |
|
|
63
28
|
|---|---|
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# Relations
|
|
2
|
+
|
|
3
|
+
This guide builds a small blog schema with `defineTable` (PostgreSQL): users, profiles, posts, comments and tags. It covers each relation kind and how to read, filter and write through it. For every option, see the [`defineTable` reference](../api-reference/table.md#foreign-keys).
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## The schema
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
// src/model/index.ts
|
|
11
|
+
import { defineTable } from 'express-file-cluster';
|
|
12
|
+
|
|
13
|
+
export const User = defineTable('User', {
|
|
14
|
+
email: { type: 'string', required: true, unique: true },
|
|
15
|
+
role: { type: 'string', enum: ['user', 'admin'], default: 'user' },
|
|
16
|
+
}, {
|
|
17
|
+
relations: {
|
|
18
|
+
posts: { hasMany: 'Post', foreignKey: 'author' }, // the other side of Post.author
|
|
19
|
+
profile: { hasOne: 'Profile', foreignKey: 'user' }, // Profile.user is unique
|
|
20
|
+
},
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
export const Profile = defineTable('Profile', {
|
|
24
|
+
user: { type: 'uuid', ref: 'User', required: true, unique: true, onDelete: 'cascade' },
|
|
25
|
+
bio: { type: 'string' },
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
export const Tag = defineTable('Tag', {
|
|
29
|
+
label: { type: 'string', required: true, unique: true },
|
|
30
|
+
}, {
|
|
31
|
+
relations: { posts: { hasMany: 'Post', foreignKey: 'tags' } },
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
export const Post = defineTable('Post', {
|
|
35
|
+
title: { type: 'string', required: true },
|
|
36
|
+
published: { type: 'boolean', default: false },
|
|
37
|
+
author: { type: 'uuid', ref: 'User', required: true, onDelete: 'cascade' }, // belongs to
|
|
38
|
+
tags: { type: 'array', of: 'uuid', ref: 'Tag' }, // many-to-many
|
|
39
|
+
}, {
|
|
40
|
+
relations: { comments: { hasMany: 'Comment', foreignKey: 'post' } },
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
export const Comment = defineTable('Comment', {
|
|
44
|
+
post: { type: 'uuid', ref: 'Post', required: true, onDelete: 'cascade' },
|
|
45
|
+
body: { type: 'string', required: true },
|
|
46
|
+
approved: { type: 'boolean', default: false },
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
// typed includes: register the models once
|
|
50
|
+
declare module 'express-file-cluster' {
|
|
51
|
+
interface Tables {
|
|
52
|
+
User: typeof User; Profile: typeof Profile; Tag: typeof Tag; Post: typeof Post; Comment: typeof Comment;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
What each piece creates on the first sync:
|
|
58
|
+
|
|
59
|
+
| Declared | In the database |
|
|
60
|
+
|---|---|
|
|
61
|
+
| `author: { type: 'uuid', ref: 'User' }` | an `author` column, a foreign key to `users(id)`, an index |
|
|
62
|
+
| `tags: { type: 'array', of: 'uuid', ref: 'Tag' }` | a join table `posts_tags` (`owner_id`, `ref_id`, `position`), cascading both ways |
|
|
63
|
+
| `relations: { posts: { hasMany … } }` | nothing: it reads `Post.author` from the other side |
|
|
64
|
+
| `relations: { profile: { hasOne … } }` | nothing, but `Profile.user` must be `unique` |
|
|
65
|
+
|
|
66
|
+
Records hold ids, not objects: `post.author` is a string and `post.tags` is a `string[]`. `include` swaps them for records when you ask.
|
|
67
|
+
|
|
68
|
+
## Reading with `include`
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
const post = await Post.findUnique({
|
|
72
|
+
where: { id },
|
|
73
|
+
include: {
|
|
74
|
+
author: { select: { email: true } },
|
|
75
|
+
tags: true,
|
|
76
|
+
comments: { where: { approved: true }, orderBy: { createdAt: 'desc' }, take: 10 },
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
// { id, title, …, author: { email }, tags: [{ id, label, … }], comments: [{ … }] }
|
|
80
|
+
|
|
81
|
+
const users = await User.findMany({
|
|
82
|
+
include: { profile: true, posts: { where: { published: true }, include: { tags: true } } },
|
|
83
|
+
});
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
However deep the `include` goes, the call runs **one SQL statement**. Turn on `logging.queries` to see the statement count per call.
|
|
87
|
+
|
|
88
|
+
## Filtering by relation
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
await User.findMany({ where: { posts: { some: { published: true } } } }); // has a published post
|
|
92
|
+
await User.findMany({ where: { posts: { none: {} } } }); // no posts at all
|
|
93
|
+
await Post.findMany({ where: { author: { is: { role: 'admin' } } } }); // by an admin
|
|
94
|
+
await Post.findMany({ where: { tags: { every: { label: { startsWith: 'pub-' } } } } });
|
|
95
|
+
await Post.findMany({ where: { comments: { some: { approved: false } } } }); // needs moderation
|
|
96
|
+
await Post.findMany({ where: { tags: { has: tagId } } }); // by id, no join
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
To-many relations take `some` / `every` / `none`. To-one relations take `is` / `isNot` (or `null`). They nest, and work anywhere `where` does: `count`, `updateMany`, `deleteMany`, and inside `include`.
|
|
100
|
+
|
|
101
|
+
## Writing through relations
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
// create a post, connect its author, create or connect tags, add a first comment: one transaction
|
|
105
|
+
const post = await Post.create({
|
|
106
|
+
data: {
|
|
107
|
+
title: 'Hello',
|
|
108
|
+
author: { connect: { email: 'ann@example.com' } },
|
|
109
|
+
tags: { connectOrCreate: [{ where: { label: 'news' }, create: { label: 'news' } }] },
|
|
110
|
+
comments: { create: [{ body: 'First!' }] },
|
|
111
|
+
},
|
|
112
|
+
include: { tags: true, comments: true },
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
await Post.update({ where: { id: post.id }, data: { tags: { push: launchTagId } } });
|
|
116
|
+
await Post.update({ where: { id: post.id }, data: { tags: { set: [] } } });
|
|
117
|
+
|
|
118
|
+
await User.update({
|
|
119
|
+
where: { id: userId },
|
|
120
|
+
data: {
|
|
121
|
+
profile: { create: { bio: 'Writes about Postgres' } }, // has one already? add delete: true
|
|
122
|
+
posts: { deleteMany: { published: false } }, // drop their drafts
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
A `connect` that matches nothing is a **400** on that field, and nothing is written. A `hasOne` `create` or `connect` unlinks the current profile, if there is one. `Profile.user` is required, so here it can't be unlinked: write `profile: { delete: true, create: { … } }` to replace it. `createMany` and `updateMany` don't take nested writes.
|
|
128
|
+
|
|
129
|
+
## Deleting
|
|
130
|
+
|
|
131
|
+
`onDelete` on the ref field decides what happens to the records pointing at a deleted one:
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
await User.delete({ where: { id } }); // cascades: profile, posts, and (through posts) comments go too
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
With the default `onDelete: 'restrict'` the same delete would be a **409** while posts still point at the user. `'setNull'` clears the field instead, so it can't be used on `required` fields. Join-table links are removed with either side.
|
|
138
|
+
|
|
139
|
+
## On MongoDB, or with `defineModel`
|
|
140
|
+
|
|
141
|
+
`defineModel` keeps relations portable: a `ref` is a plain id field on both engines, with no foreign key, and `populate` resolves it in a batched second query:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
await Post.find({ published: true }, { populate: 'author' });
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
There is no `include`, relation filtering or nested writes there. For those, use `defineTable` on PostgreSQL. See [Which model API?](./which-api.md).
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# Which model API?
|
|
2
|
+
|
|
3
|
+
EFC has two ways to define a model. They share one foundation: the schema format, inferred types, validation, auto-sync, `transaction()`, undeclared-field rules and errors. They differ in which engines they run on and in their query vocabulary.
|
|
4
|
+
|
|
5
|
+
| | `defineModel` | `defineTable` |
|
|
6
|
+
|---|---|---|
|
|
7
|
+
| Engine | MongoDB or PostgreSQL (set by `DATABASE_URL`) | PostgreSQL only |
|
|
8
|
+
| Queries | mongoose-style: `find(filter, { sort, limit, populate })`, `$set`, `$inc` | Prisma-style: `findMany({ where, include, orderBy, take, cursor })`, `findUnique`, `upsert`, `groupBy`, `aggregate` |
|
|
9
|
+
| Relations | `ref` + `populate` (a plain column on PostgreSQL) | real foreign keys, many-to-many join tables, `include` in one SQL statement, relation filters, nested writes |
|
|
10
|
+
| Field types | the portable set (`string`, `number`, `boolean`, `date`, `objectId`, objects, arrays) | + `integer`, `bigint`, `decimal`, `uuid`, `json`, `varchar`, native arrays and enums, `serial` ids |
|
|
11
|
+
| Migrations | auto-sync, `efc db generate` | auto-sync, `efc db generate`, `efc db pull`, `efc import-prisma` |
|
|
12
|
+
| Wrong engine | — | fails at first use with an `[EFC]` error naming the model |
|
|
13
|
+
|
|
14
|
+
## Pick one
|
|
15
|
+
|
|
16
|
+
- **Building on PostgreSQL:** use `defineTable`. You get foreign keys, joins and SQL types. `create-efc-app` generates `defineTable` models for PostgreSQL apps.
|
|
17
|
+
- **Building on MongoDB:** use `defineModel`. On MongoDB it *is* mongoose underneath (`Model.raw()` hands you the mongoose model), with `aggregate()`, TTL indexes and transactions on a replica set.
|
|
18
|
+
- **The app may switch engines, or ships to both:** use `defineModel` and stay inside the shared filter and update subset (`$eq $ne $gt $gte $lt $lte $in $nin $exists $regex $and $or`; `$set $unset $inc $push $pull`).
|
|
19
|
+
- **Coming from Prisma:** use `defineTable`. `efc import-prisma` writes the models for you. See [Coming from Prisma](./coming-from-prisma.md).
|
|
20
|
+
|
|
21
|
+
## The same query, both ways
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
// defineModel
|
|
25
|
+
const posts = await Post.find(
|
|
26
|
+
{ status: 'published', views: { $gte: 100 } },
|
|
27
|
+
{ sort: { createdAt: -1 }, limit: 20, populate: 'author' },
|
|
28
|
+
);
|
|
29
|
+
await Post.update(id, { $inc: { views: 1 } });
|
|
30
|
+
|
|
31
|
+
// defineTable
|
|
32
|
+
const posts = await Post.findMany({
|
|
33
|
+
where: { status: 'published', views: { gte: 100 } },
|
|
34
|
+
orderBy: { createdAt: 'desc' },
|
|
35
|
+
take: 20,
|
|
36
|
+
include: { author: true },
|
|
37
|
+
});
|
|
38
|
+
await Post.update({ where: { id }, data: { views: { increment: 1 } } });
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Moving between them
|
|
42
|
+
|
|
43
|
+
On PostgreSQL, a `defineModel` and a `defineTable` over the same table read and write the same records, so you can move one model at a time. Two things change on the way:
|
|
44
|
+
|
|
45
|
+
- A `ref` becomes a real foreign key. The field's `type` must match the target's id (`uuid` for the default id, `integer` for `id: 'serial'`). Rows pointing at missing records don't block the deploy: the key is added `NOT VALID`, and validation is skipped with a warning naming the count.
|
|
46
|
+
- An array of refs (a `jsonb` column under `defineModel`) moves into a join table on the first sync. The old column is kept but no longer read, so don't keep a `defineModel` writing that field afterwards.
|
|
47
|
+
|
|
48
|
+
Run `efc db sync --dry-run` before you switch to see exactly what will change.
|
|
49
|
+
|
|
50
|
+
See also: [Database guide](./database.md) · [Relations](./relations.md) · [`defineModel` API](../api-reference/db.md) · [`defineTable` API](../api-reference/table.md)
|
package/dist/docs/index.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
**express-file-cluster (EFC)** is an opinionated backend framework built on Express. It removes routing ceremony, saturates every CPU core automatically, and ships a production-grade background-task subsystem — all from a single `ignite()` call.
|
|
4
4
|
|
|
5
|
-
> **Status: v0.
|
|
5
|
+
> **Status: v0.9.0 — Beta.** File-based routing (incl. catch-all and optional segments), request validation, clustering, auth, structured logging, MongoDB and PostgreSQL models with types inferred from the schema, PostgreSQL-native `defineTable` (Prisma-style queries and relations: foreign keys, many-to-many, `include`, relation filters, nested writes), query logging, BullMQ and pg-boss tasks with cron and dead-letter tooling, migrations (written for you from model changes: `efc db generate`, plus `efc db pull` and `efc import-prisma`), and the `efc add` feature registry (auth, admin, billing… copied into your app as source you own) are all implemented.
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
| [Getting Started](./getting-started/index.md) | Scaffold a project, understand the structure |
|
|
27
27
|
| [Core Concepts](./core-concepts/index.md) | The four pillars: routing, clustering, tasks, middleware |
|
|
28
28
|
| [API Reference](./api-reference/ignite.md) | Every exported function and type, fully documented |
|
|
29
|
-
| [Guides](./guides/authentication.md) | Deep-dives: auth, database, RBAC, mailer, error handling, deployment |
|
|
29
|
+
| [Guides](./guides/authentication.md) | Deep-dives: auth, OAuth, database, RBAC, mailer, error handling, deployment |
|
|
30
30
|
| [CLI](./cli/index.md) | All `efc` commands with flags and examples |
|
|
31
31
|
| [Contributing](./contributing/index.md) | Roadmap, branch conventions, PR requirements |
|
|
32
32
|
|
|
@@ -37,13 +37,17 @@
|
|
|
37
37
|
| [Authentication](./guides/authentication.md) | JWT strategies, login/logout, `requireAuth` |
|
|
38
38
|
| [RBAC](./guides/rbac.md) | Role-based route protection via the `requireAuth('role')` shorthand |
|
|
39
39
|
| [Database](./guides/database.md) | `defineModel`, queries, transactions, MongoDB vs PostgreSQL |
|
|
40
|
+
| [Which model API?](./guides/which-api.md) | `defineModel` vs `defineTable`, and moving between them |
|
|
41
|
+
| [Relations](./guides/relations.md) | Foreign keys, many-to-many, `include`, relation filters, nested writes |
|
|
40
42
|
| [defineTable](./api-reference/table.md) | PostgreSQL-native models: Prisma-style queries, SQL types, aggregation |
|
|
41
|
-
| [Migrations & Seeds](./guides/migrations.md) | `efc db migrate / rollback / seed / studio
|
|
43
|
+
| [Migrations & Seeds](./guides/migrations.md) | `efc db generate / migrate / rollback / pull / seed / studio`, drift checks |
|
|
44
|
+
| [Coming from Prisma](./guides/coming-from-prisma.md) | `efc import-prisma`, schema and query mapping |
|
|
42
45
|
| [Validation](./guides/validation.md) | Route `schema` exports with zod, valibot, arktype |
|
|
43
46
|
| [Logging](./guides/logging.md) | pino, request IDs, `getLogger()` |
|
|
44
47
|
| [Caching & Sessions](./guides/caching.md) | `cache`, `cacheResponse`, revoking JWT sessions |
|
|
45
48
|
| [Generated Portals](./guides/generated-portals.md) | Every model and route `create-efc-app` scaffolds for the User/Admin portals |
|
|
46
49
|
| [Mailer](./guides/mailer.md) | Gmail (app password) and custom SMTP setup, sending email from a task |
|
|
50
|
+
| [Sign in with Google & Apple](./guides/oauth.md) | `efc add auth@google` / `auth@apple`: setup, flow, account linking |
|
|
47
51
|
| [Environment Variables](./guides/environment-variables.md) | Full `.env` reference |
|
|
48
52
|
| [Error Handling](./guides/error-handling.md) | `HttpError`, custom handlers, task failures |
|
|
49
53
|
| [Deployment](./guides/deployment.md) | Build, start, and ship to production |
|
|
@@ -37,8 +37,8 @@ Load **only** the module the work points to. Each is self-contained.
|
|
|
37
37
|
docs/ ← full documentation
|
|
38
38
|
```
|
|
39
39
|
|
|
40
|
-
## Status (v0.
|
|
40
|
+
## Status (v0.9.0 — Beta, Phase 2 complete + defineTable with relations + generated migrations + `efc add` registry)
|
|
41
41
|
|
|
42
|
-
Implemented: file-based router (incl. `[[id]]`, `[...slug]`, `[[...slug]]`), request validation (`export const schema`, Standard Schema), multi-core clustering with graceful shutdown, http-only + localStorage auth, structured logging (pino, request IDs), `defineModel` on MongoDB (mongoose) **and** PostgreSQL (Drizzle) with validation, query options, bulk ops, transactions, `sync()`/`drop()`, PostgreSQL-native `defineTable` (Prisma-style queries, foreign keys, many-to-many, `include`, relation filters, nested writes), query logging (`logging.queries`), BullMQ **and** pg-boss task backends with cron schedules and dead-letter CLI, worker_threads for CPU-bound tasks, migrations/seeds/studio (`efc db`), full CLI.
|
|
42
|
+
Implemented: file-based router (incl. `[[id]]`, `[...slug]`, `[[...slug]]`), request validation (`export const schema`, Standard Schema), multi-core clustering with graceful shutdown, http-only + localStorage auth, structured logging (pino, request IDs), `defineModel` on MongoDB (mongoose) **and** PostgreSQL (Drizzle) with validation, query options, bulk ops, transactions, `sync()`/`drop()`, PostgreSQL-native `defineTable` (Prisma-style queries, foreign keys, many-to-many, `include`, relation filters, nested writes), query logging (`logging.queries`), BullMQ **and** pg-boss task backends with cron schedules and dead-letter CLI, worker_threads for CPU-bound tasks, migrations/seeds/studio (`efc db`) incl. migrations generated from model diffs (`efc db generate`), `efc db pull` and `efc import-prisma`, full CLI.
|
|
43
43
|
|
|
44
|
-
**Not yet implemented (Phase 3+):** WebSockets, plugins, OpenAPI generation, OpenTelemetry, `efc lint`, `efc deploy`,
|
|
44
|
+
**Not yet implemented (Phase 3+):** WebSockets, plugins, OpenAPI generation, OpenTelemetry, `efc lint`, `efc deploy`, `defineCollection`.
|
|
@@ -91,6 +91,7 @@ interface EFCConfig {
|
|
|
91
91
|
dashboard?: boolean; // dev-only route docs at '/'
|
|
92
92
|
database?: 'mongodb' | 'postgresql'; // default: inferred from databaseUrl scheme
|
|
93
93
|
databaseUrl?: string;
|
|
94
|
+
databasePool?: { max?: number; idleTimeoutMs?: number; connectionTimeoutMs?: number }; // per worker
|
|
94
95
|
authStrategy?: 'http-only' | 'localStorage';
|
|
95
96
|
jwtSecret?: string;
|
|
96
97
|
jwtExpiresIn?: string; // default '7d'
|
|
@@ -133,12 +133,24 @@ export default async function(req, res) { ... } // NOT called as a route handl
|
|
|
133
133
|
```bash
|
|
134
134
|
efc lint # NOT IMPLEMENTED
|
|
135
135
|
efc deploy # NOT IMPLEMENTED
|
|
136
|
-
efc db generate # NOT IMPLEMENTED — no schema-diff migration generator; write migrations
|
|
137
|
-
# by hand (efc generate migration <name>) and call Model.sync()
|
|
138
136
|
efc db reset / fresh # NOT IMPLEMENTED
|
|
137
|
+
efc db push # NOT IMPLEMENTED — that's `efc db sync` (or autoSync)
|
|
138
|
+
efc db pull # PostgreSQL only — MongoDB is NOT supported (exits with an error)
|
|
139
|
+
efc remove <item> # NOT IMPLEMENTED — `efc add` copies files; delete them yourself
|
|
140
|
+
efc add <url|@ns/x> # NOT IMPLEMENTED — only the built-in registry (efc list); no third-party registries
|
|
139
141
|
```
|
|
140
142
|
|
|
141
|
-
|
|
143
|
+
`efc add | list | view | diff | init` DO exist (the feature registry, `docs/cli/add.md`).
|
|
144
|
+
OAuth sign-in exists only as registry items (`efc add auth@google`, `efc add auth@apple`) —
|
|
145
|
+
app code in `src/api/auth/<provider>/` + `src/lib/oauth`; there is NO framework OAuth API
|
|
146
|
+
(no `passport`, no `oauth` option on `ignite()`, no other providers).
|
|
147
|
+
|
|
148
|
+
Implemented commands: `start dev|prod`, `build prod`, `run tests`, `generate route|task|middleware|migration|seed`, `db generate|migrate|rollback|status|sync|pull|seed|studio`, `import-prisma`, `routes`, `tasks` (+ `failed|retry|purge`), `doctor`, `--version`.
|
|
149
|
+
|
|
150
|
+
`efc db generate [name] [--allow-drop] [--tighten] [--verify]` DOES exist: it replays the
|
|
151
|
+
migrations into a throwaway schema/database, diffs the models against it and writes
|
|
152
|
+
`src/migrations/<ts>_<name>.(ts|js)`. Flags: `efc db sync --dry-run --exit-code` (exit 2 on
|
|
153
|
+
drift), `efc db migrate --baseline` (record as applied without running).
|
|
142
154
|
|
|
143
155
|
---
|
|
144
156
|
|
|
@@ -150,9 +162,13 @@ Implemented commands: `start dev|prod`, `build prod`, `run tests`, `generate rou
|
|
|
150
162
|
// ✅ Tables are created and reconciled automatically on first use (autoSync, default on):
|
|
151
163
|
// add column, change type (with cast), drop stale NOT NULL, rebuild enum CHECK,
|
|
152
164
|
// create/drop EFC-named indexes. `efc db sync --dry-run` prints the SQL.
|
|
153
|
-
//
|
|
154
|
-
//
|
|
155
|
-
// ❌
|
|
165
|
+
// ✅ Sync RENAMES a column when the field declares `renamedFrom: 'oldName'` (PostgreSQL);
|
|
166
|
+
// on MongoDB `efc db generate` writes the `$rename` migration.
|
|
167
|
+
// ❌ Sync never DROPS columns, never adds NOT NULL and never deletes rows — that's
|
|
168
|
+
// `efc db generate <name> --allow-drop` / `--tighten` (explicit, reviewed migrations).
|
|
169
|
+
// Splits and backfills still need a hand-written migration (db.query()).
|
|
170
|
+
// ✅ `efc db generate` writes migrations from model diffs; `efc db pull` (PostgreSQL) and
|
|
171
|
+
// `efc import-prisma` write defineTable model files.
|
|
156
172
|
// ❌ No joins in the model API — populate does a second query; for SQL joins use
|
|
157
173
|
// Drizzle via Model.raw() or db.query().
|
|
158
174
|
// ❌ aggregate() is MongoDB-only (rejects on PostgreSQL).
|