express-file-cluster 0.8.0 → 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 +1 -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-OSES7ZQ5.js → chunk-2PBMLMO4.js} +2 -2
- package/dist/{chunk-75O3WQKR.cjs → chunk-66R7S7J3.cjs} +5 -5
- package/dist/{chunk-75O3WQKR.cjs.map → chunk-66R7S7J3.cjs.map} +1 -1
- package/dist/{chunk-B2I7SYQ3.js → chunk-6QNLN6AI.js} +20 -7
- package/dist/chunk-6QNLN6AI.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-FQFKHPLR.cjs → chunk-RGTENTDN.cjs} +121 -108
- 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 +19 -19
- package/dist/cli/db-runner.js +3 -3
- package/dist/cli/index.cjs +3 -3
- package/dist/cli/index.js +2 -2
- package/dist/docs/api-reference/ignite.md +19 -0
- package/dist/docs/api-reference/table.md +3 -0
- package/dist/docs/cli/add.md +1 -1
- package/dist/docs/guides/database.md +2 -0
- package/dist/docs/guides/relations.md +147 -0
- package/dist/docs/guides/which-api.md +50 -0
- package/dist/docs/index.md +3 -1
- package/dist/docs/skills/SKILL.md +1 -1
- package/dist/docs/skills/api-surface.md +1 -0
- package/dist/index.cjs +19 -19
- 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 +6 -6
- package/dist/index.js.map +1 -1
- package/dist/registry/index.json +1 -1
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/{types-B1tJoI4g.d.ts → types-gyvA7BtO.d.cts} +12 -1
- package/dist/{types-B1tJoI4g.d.cts → types-gyvA7BtO.d.ts} +12 -1
- package/package.json +1 -1
- package/dist/chunk-B2I7SYQ3.js.map +0 -1
- package/dist/chunk-BUBXO7WU.js.map +0 -1
- package/dist/chunk-FQFKHPLR.cjs.map +0 -1
- package/dist/chunk-MGH4VDV3.cjs.map +0 -1
- /package/dist/{chunk-OSES7ZQ5.js.map → chunk-2PBMLMO4.js.map} +0 -0
- /package/dist/{chunk-TRC4DUZB.js.map → chunk-RSZB7VAO.js.map} +0 -0
package/dist/cli/db-runner.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict"; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var
|
|
4
|
+
var _chunkRGTENTDNcjs = require('../chunk-RGTENTDN.cjs');
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
@@ -17,11 +17,11 @@ var _chunkQL6EWT4Bcjs = require('../chunk-QL6EWT4B.cjs');
|
|
|
17
17
|
|
|
18
18
|
|
|
19
19
|
|
|
20
|
-
var
|
|
20
|
+
var _chunk66R7S7J3cjs = require('../chunk-66R7S7J3.cjs');
|
|
21
21
|
|
|
22
22
|
|
|
23
23
|
|
|
24
|
-
var
|
|
24
|
+
var _chunkVQSWSYK6cjs = require('../chunk-VQSWSYK6.cjs');
|
|
25
25
|
|
|
26
26
|
|
|
27
27
|
var _chunkYL37D6KMcjs = require('../chunk-YL37D6KM.cjs');
|
|
@@ -595,14 +595,14 @@ async function pullPostgres(pool) {
|
|
|
595
595
|
const cols = colsOf(table);
|
|
596
596
|
const notes = [];
|
|
597
597
|
const underscored = cols.filter((c) => c.name.includes("_"));
|
|
598
|
-
const snake = underscored.length > 0 && underscored.every((c) =>
|
|
598
|
+
const snake = underscored.length > 0 && underscored.every((c) => _chunk66R7S7J3cjs.snakeCase.call(void 0, _chunkQL6EWT4Bcjs.camel.call(void 0, c.name)) === c.name);
|
|
599
599
|
const fieldOf = (column) => snake ? _chunkQL6EWT4Bcjs.camel.call(void 0, column) : column;
|
|
600
600
|
const options = {};
|
|
601
601
|
if (snake) options["naming"] = "snake_case";
|
|
602
602
|
if (idKind !== "uuid") options["id"] = idKind;
|
|
603
|
-
const defaultTable =
|
|
603
|
+
const defaultTable = _chunk66R7S7J3cjs.tableNameFor.call(void 0, snake ? _chunk66R7S7J3cjs.snakeCase.call(void 0, name) : name);
|
|
604
604
|
if (defaultTable !== table) options["collection"] = table;
|
|
605
|
-
const tsColumn = (f) => cols.find((c) => c.name === (snake ?
|
|
605
|
+
const tsColumn = (f) => cols.find((c) => c.name === (snake ? _chunk66R7S7J3cjs.snakeCase.call(void 0, f) : f));
|
|
606
606
|
const isTs = (c) => _optionalChain([c, 'optionalAccess', _19 => _19.type]) === "timestamp with time zone";
|
|
607
607
|
const hasCreated = isTs(tsColumn("createdAt"));
|
|
608
608
|
const hasUpdated = isTs(tsColumn("updatedAt"));
|
|
@@ -659,7 +659,7 @@ async function pullPostgres(pool) {
|
|
|
659
659
|
def["default"] = /^'((?:[^']|'')*)'/.exec(d)[1].replace(/''/g, "'");
|
|
660
660
|
else notes.push(`${field}: database default ${d} not carried over`);
|
|
661
661
|
}
|
|
662
|
-
if ((snake ?
|
|
662
|
+
if ((snake ? _chunk66R7S7J3cjs.snakeCase.call(void 0, field) : field) !== col.name) def["column"] = col.name;
|
|
663
663
|
const fk = tableFks.find((f) => f.columns.length === 1 && f.columns[0] === col.name);
|
|
664
664
|
if (fk) {
|
|
665
665
|
const target = modelName(fk.target);
|
|
@@ -702,7 +702,7 @@ async function pullPostgres(pool) {
|
|
|
702
702
|
const of = target.idKind === "uuid" ? "uuid" : target.idKind === "bigserial" ? "bigint" : "integer";
|
|
703
703
|
fields.push([fieldOf(j.column), { type: "array", of, ref: target.name }]);
|
|
704
704
|
}
|
|
705
|
-
const fieldOfColumn = (c) => _nullishCoalesce(_optionalChain([fields, 'access', _31 => _31.find, 'call', _32 => _32(([f, d]) => (_nullishCoalesce(d["column"], () => ( (snake ?
|
|
705
|
+
const fieldOfColumn = (c) => _nullishCoalesce(_optionalChain([fields, 'access', _31 => _31.find, 'call', _32 => _32(([f, d]) => (_nullishCoalesce(d["column"], () => ( (snake ? _chunk66R7S7J3cjs.snakeCase.call(void 0, f) : f)))) === c), 'optionalAccess', _33 => _33[0]]), () => ( fieldOf(c)));
|
|
706
706
|
const indexDefs = [];
|
|
707
707
|
for (const idx of tableIndexes) {
|
|
708
708
|
if (usedIndexes.has(idx.name)) continue;
|
|
@@ -786,7 +786,7 @@ async function importModels(root) {
|
|
|
786
786
|
walk(_path2.default.join(root, "model"));
|
|
787
787
|
walk(_path2.default.join(root, "models"));
|
|
788
788
|
for (const f of files.sort()) await Promise.resolve().then(() => _interopRequireWildcard(require(_url.pathToFileURL.call(void 0, f).href)));
|
|
789
|
-
return
|
|
789
|
+
return _chunk66R7S7J3cjs.registeredModels.call(void 0, );
|
|
790
790
|
}
|
|
791
791
|
function shadowUrl(url, engine, name) {
|
|
792
792
|
if (engine === "mongodb")
|
|
@@ -816,12 +816,12 @@ async function main() {
|
|
|
816
816
|
if (!url)
|
|
817
817
|
throw new Error("[EFC] DATABASE_URL is not set (add it to .env or pass --database-url)");
|
|
818
818
|
const engine = engineOf(url);
|
|
819
|
-
|
|
820
|
-
let client = engine === "mongodb" ? await
|
|
821
|
-
|
|
819
|
+
_chunk66R7S7J3cjs.setDbEngine.call(void 0, engine);
|
|
820
|
+
let client = engine === "mongodb" ? await _chunkRGTENTDNcjs.connectMongo.call(void 0, url) : await _chunkVQSWSYK6cjs.connectPostgres.call(void 0, url);
|
|
821
|
+
_chunkRGTENTDNcjs.setDbClient.call(void 0, client);
|
|
822
822
|
const close = async () => {
|
|
823
823
|
if (engine === "mongodb") await client.close();
|
|
824
|
-
else await
|
|
824
|
+
else await _chunkVQSWSYK6cjs.closePostgres.call(void 0, );
|
|
825
825
|
};
|
|
826
826
|
const migrations = _path2.default.join(opts.root, "migrations");
|
|
827
827
|
const step = (verb) => (name) => console.log(` ${_picocolors2.default.cyan(verb)} ${name}`);
|
|
@@ -854,7 +854,7 @@ async function main() {
|
|
|
854
854
|
break;
|
|
855
855
|
}
|
|
856
856
|
case "sync": {
|
|
857
|
-
|
|
857
|
+
_chunk66R7S7J3cjs.setAutoSync.call(void 0, false);
|
|
858
858
|
const models = await importModels(opts.root);
|
|
859
859
|
if (models.length === 0) {
|
|
860
860
|
console.log(
|
|
@@ -889,16 +889,16 @@ async function main() {
|
|
|
889
889
|
);
|
|
890
890
|
}
|
|
891
891
|
await close();
|
|
892
|
-
client = engine === "mongodb" ? await
|
|
893
|
-
|
|
892
|
+
client = engine === "mongodb" ? await _chunkRGTENTDNcjs.connectMongo.call(void 0, shadowUrl(url, engine, shadow)) : await _chunkVQSWSYK6cjs.connectPostgres.call(void 0, shadowUrl(url, engine, shadow));
|
|
893
|
+
_chunkRGTENTDNcjs.setDbClient.call(void 0, client);
|
|
894
894
|
try {
|
|
895
|
-
|
|
895
|
+
_chunk66R7S7J3cjs.setAutoSync.call(void 0, false);
|
|
896
896
|
const migrator = new Migrator(migrations, engine, client);
|
|
897
|
-
|
|
897
|
+
_chunk66R7S7J3cjs.setSyncSuppressed.call(void 0, true);
|
|
898
898
|
try {
|
|
899
899
|
await migrator.migrate();
|
|
900
900
|
} finally {
|
|
901
|
-
|
|
901
|
+
_chunk66R7S7J3cjs.setSyncSuppressed.call(void 0, false);
|
|
902
902
|
}
|
|
903
903
|
const models = await importModels(opts.root);
|
|
904
904
|
if (models.length === 0) {
|
package/dist/cli/db-runner.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
connectMongo,
|
|
3
3
|
setDbClient
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-6QNLN6AI.js";
|
|
5
5
|
import {
|
|
6
6
|
camel,
|
|
7
7
|
lcFirst,
|
|
@@ -17,11 +17,11 @@ import {
|
|
|
17
17
|
setSyncSuppressed,
|
|
18
18
|
snakeCase,
|
|
19
19
|
tableNameFor
|
|
20
|
-
} from "../chunk-
|
|
20
|
+
} from "../chunk-2PBMLMO4.js";
|
|
21
21
|
import {
|
|
22
22
|
closePostgres,
|
|
23
23
|
connectPostgres
|
|
24
|
-
} from "../chunk-
|
|
24
|
+
} from "../chunk-HXV543HZ.js";
|
|
25
25
|
import {
|
|
26
26
|
configureLogger
|
|
27
27
|
} from "../chunk-277BSYVH.js";
|
package/dist/cli/index.cjs
CHANGED
|
@@ -10,8 +10,8 @@ var _chunkT4OHFU5Tcjs = require('../chunk-T4OHFU5T.cjs');
|
|
|
10
10
|
var _chunkQL6EWT4Bcjs = require('../chunk-QL6EWT4B.cjs');
|
|
11
11
|
|
|
12
12
|
|
|
13
|
-
var
|
|
14
|
-
require('../chunk-
|
|
13
|
+
var _chunk66R7S7J3cjs = require('../chunk-66R7S7J3.cjs');
|
|
14
|
+
require('../chunk-VQSWSYK6.cjs');
|
|
15
15
|
require('../chunk-7YEX4MQV.cjs');
|
|
16
16
|
require('../chunk-TI24L4XE.cjs');
|
|
17
17
|
require('../chunk-YL37D6KM.cjs');
|
|
@@ -1789,7 +1789,7 @@ function importPrisma(source) {
|
|
|
1789
1789
|
const fields = [];
|
|
1790
1790
|
const relations = {};
|
|
1791
1791
|
const table = _nullishCoalesce(unquote(arg(blocks(m, "@@map")[0])), () => ( m.name));
|
|
1792
|
-
if (table !==
|
|
1792
|
+
if (table !== _chunk66R7S7J3cjs.tableNameFor.call(void 0, m.name)) options["collection"] = table;
|
|
1793
1793
|
const kind = idKind.get(m.name);
|
|
1794
1794
|
if (kind !== "uuid") options["id"] = kind;
|
|
1795
1795
|
if (blocks(m, "@@id").length) {
|
package/dist/cli/index.js
CHANGED
|
@@ -10,8 +10,8 @@ import {
|
|
|
10
10
|
} from "../chunk-BBSZLGZW.js";
|
|
11
11
|
import {
|
|
12
12
|
tableNameFor
|
|
13
|
-
} from "../chunk-
|
|
14
|
-
import "../chunk-
|
|
13
|
+
} from "../chunk-2PBMLMO4.js";
|
|
14
|
+
import "../chunk-HXV543HZ.js";
|
|
15
15
|
import "../chunk-LJNSJFOL.js";
|
|
16
16
|
import "../chunk-HBYSKULC.js";
|
|
17
17
|
import "../chunk-277BSYVH.js";
|
|
@@ -31,6 +31,7 @@ interface EFCConfig {
|
|
|
31
31
|
// Database
|
|
32
32
|
database?: 'mongodb' | 'postgresql';
|
|
33
33
|
databaseUrl?: string;
|
|
34
|
+
databasePool?: { max?: number; idleTimeoutMs?: number; connectionTimeoutMs?: number };
|
|
34
35
|
|
|
35
36
|
// Auth
|
|
36
37
|
authStrategy?: 'http-only' | 'localStorage';
|
|
@@ -150,6 +151,24 @@ Connection string for the database. `ignite()` never reads `DATABASE_URL` from t
|
|
|
150
151
|
|
|
151
152
|
---
|
|
152
153
|
|
|
154
|
+
### `databasePool`
|
|
155
|
+
|
|
156
|
+
Connection pool settings. Each worker process has its own pool, so the database sees up to `max × workers` connections. Keep that under the server's limit (PostgreSQL's `max_connections` defaults to 100).
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
databasePool: { max: 5, idleTimeoutMs: 30_000, connectionTimeoutMs: 5_000 },
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
| Option | PostgreSQL (`pg` Pool) | MongoDB (mongoose) |
|
|
163
|
+
|---|---|---|
|
|
164
|
+
| `max` | `max` — default 10 | `maxPoolSize` — default 100 |
|
|
165
|
+
| `idleTimeoutMs` | `idleTimeoutMillis` — default 10000 | `maxIdleTimeMS` — default: never |
|
|
166
|
+
| `connectionTimeoutMs` | `connectionTimeoutMillis` — default: no limit | `serverSelectionTimeoutMS` (default 30000) and `waitQueueTimeoutMS` (default: no limit) |
|
|
167
|
+
|
|
168
|
+
Unset options keep the driver's default. `efc db` commands use the defaults.
|
|
169
|
+
|
|
170
|
+
---
|
|
171
|
+
|
|
153
172
|
### `authStrategy`
|
|
154
173
|
|
|
155
174
|
How JWTs are delivered to clients:
|
|
@@ -403,6 +403,9 @@ await User.update({
|
|
|
403
403
|
- `connect`, `disconnect`, `set` and `delete` take unique wheres (or ids); a list or a single one.
|
|
404
404
|
A `connect` that matches nothing is a **400** on the field.
|
|
405
405
|
- Children created through a back-relation get their foreign key from the parent — leave it out.
|
|
406
|
+
- On `update`, a `hasOne` `create` / `connect` / `disconnect` first unlinks the current child (its
|
|
407
|
+
foreign key is set to `null`). If that key is `required` and a child exists, it's a **400**:
|
|
408
|
+
add `delete: true` (`profile: { delete: true, create: { … } }`) to replace it.
|
|
406
409
|
- The whole call runs in **one transaction**: anything failing rolls it all back.
|
|
407
410
|
- `createMany` / `updateMany` write rows only; they refuse nested writes, as in Prisma.
|
|
408
411
|
- `upsert` with nested writes reads first, then creates or updates, in the transaction (without
|
package/dist/docs/cli/add.md
CHANGED
|
@@ -33,6 +33,8 @@ const config: EFCConfig = {
|
|
|
33
33
|
};
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
+
Not sure whether to use `defineModel` or the PostgreSQL-native `defineTable`? See [Which model API?](./which-api.md).
|
|
37
|
+
|
|
36
38
|
Each worker process connects once during Pre-Flight, before routes mount — no cold connection on the first request.
|
|
37
39
|
|
|
38
40
|
---
|
|
@@ -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
|
|
|
@@ -37,6 +37,8 @@
|
|
|
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
43
|
| [Migrations & Seeds](./guides/migrations.md) | `efc db generate / migrate / rollback / pull / seed / studio`, drift checks |
|
|
42
44
|
| [Coming from Prisma](./guides/coming-from-prisma.md) | `efc import-prisma`, schema and query mapping |
|
|
@@ -37,7 +37,7 @@ 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
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
|
|
|
@@ -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'
|
package/dist/index.cjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
|
|
7
|
-
var
|
|
7
|
+
var _chunk2J3HHQKPcjs = require('./chunk-2J3HHQKP.cjs');
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
var _chunkR34R7QPDcjs = require('./chunk-R34R7QPD.cjs');
|
|
@@ -20,18 +20,18 @@ var _chunkT4OHFU5Tcjs = require('./chunk-T4OHFU5T.cjs');
|
|
|
20
20
|
|
|
21
21
|
|
|
22
22
|
|
|
23
|
-
var
|
|
23
|
+
var _chunkRGTENTDNcjs = require('./chunk-RGTENTDN.cjs');
|
|
24
24
|
|
|
25
25
|
|
|
26
26
|
|
|
27
27
|
|
|
28
28
|
|
|
29
29
|
|
|
30
|
-
var
|
|
30
|
+
var _chunk66R7S7J3cjs = require('./chunk-66R7S7J3.cjs');
|
|
31
31
|
|
|
32
32
|
|
|
33
33
|
|
|
34
|
-
var
|
|
34
|
+
var _chunkVQSWSYK6cjs = require('./chunk-VQSWSYK6.cjs');
|
|
35
35
|
|
|
36
36
|
|
|
37
37
|
|
|
@@ -868,7 +868,7 @@ function cacheResponse(options) {
|
|
|
868
868
|
}
|
|
869
869
|
const key = RESPONSE_PREFIX + scope + (opts.key ? opts.key(req) : req.originalUrl);
|
|
870
870
|
void (async () => {
|
|
871
|
-
const hit = await
|
|
871
|
+
const hit = await _chunk2J3HHQKPcjs.cache.get(key);
|
|
872
872
|
if (hit) {
|
|
873
873
|
res.setHeader("X-Cache", "HIT");
|
|
874
874
|
res.status(hit.status).json(hit.body);
|
|
@@ -877,7 +877,7 @@ function cacheResponse(options) {
|
|
|
877
877
|
res.setHeader("X-Cache", "MISS");
|
|
878
878
|
const json = res.json.bind(res);
|
|
879
879
|
res.json = (body) => {
|
|
880
|
-
if (res.statusCode === 200) void
|
|
880
|
+
if (res.statusCode === 200) void _chunk2J3HHQKPcjs.cache.set(key, { status: 200, body }, { ttl: opts.ttl });
|
|
881
881
|
return json(body);
|
|
882
882
|
};
|
|
883
883
|
next();
|
|
@@ -952,10 +952,10 @@ async function ignite(config) {
|
|
|
952
952
|
const authStrategy = _nullishCoalesce(config.authStrategy, () => ( "http-only"));
|
|
953
953
|
const clusterEnabled = _nullishCoalesce(config.cluster, () => ( process.env["NODE_ENV"] === "production"));
|
|
954
954
|
_chunkYL37D6KMcjs.configureLogger.call(void 0, config.logging);
|
|
955
|
-
|
|
955
|
+
_chunkVQSWSYK6cjs.configureQueryLog.call(void 0, config.logging);
|
|
956
956
|
if (clusterEnabled && _cluster2.default.isPrimary) {
|
|
957
957
|
if (config.cache && config.cache.backend === "memory") {
|
|
958
|
-
|
|
958
|
+
_chunk2J3HHQKPcjs.servePrimaryCache.call(void 0, _nullishCoalesce(config.cache.maxEntries, () => ( 1e4)));
|
|
959
959
|
}
|
|
960
960
|
runMaster({
|
|
961
961
|
workers: _nullishCoalesce(workers, () => ( _os2.default.cpus().length)),
|
|
@@ -997,20 +997,20 @@ async function ignite(config) {
|
|
|
997
997
|
for (const mw of globalMiddlewares) {
|
|
998
998
|
app.use(mw);
|
|
999
999
|
}
|
|
1000
|
-
if (database)
|
|
1001
|
-
|
|
1000
|
+
if (database) _chunk66R7S7J3cjs.setDbEngine.call(void 0, database);
|
|
1001
|
+
_chunk66R7S7J3cjs.setAutoSync.call(void 0, _nullishCoalesce(config.autoSync, () => ( true)));
|
|
1002
1002
|
if (database === "mongodb" && databaseUrl) {
|
|
1003
|
-
const conn = await
|
|
1004
|
-
|
|
1003
|
+
const conn = await _chunkRGTENTDNcjs.connectMongo.call(void 0, databaseUrl, config.databasePool);
|
|
1004
|
+
_chunkRGTENTDNcjs.setDbClient.call(void 0, conn);
|
|
1005
1005
|
} else if (database === "postgresql" && databaseUrl) {
|
|
1006
|
-
const pool = await
|
|
1007
|
-
|
|
1006
|
+
const pool = await _chunkVQSWSYK6cjs.connectPostgres.call(void 0, databaseUrl, config.databasePool);
|
|
1007
|
+
_chunkRGTENTDNcjs.setDbClient.call(void 0, pool);
|
|
1008
1008
|
}
|
|
1009
1009
|
if (config.cache) {
|
|
1010
|
-
await
|
|
1010
|
+
await _chunk2J3HHQKPcjs.configureCache.call(void 0, config.cache);
|
|
1011
1011
|
}
|
|
1012
1012
|
if (jwtSecret) {
|
|
1013
|
-
|
|
1013
|
+
_chunk2J3HHQKPcjs.configureAuth.call(void 0, {
|
|
1014
1014
|
secret: jwtSecret,
|
|
1015
1015
|
strategy: authStrategy,
|
|
1016
1016
|
expiresIn: _nullishCoalesce(config.jwtExpiresIn, () => ( "7d")),
|
|
@@ -1065,7 +1065,7 @@ async function ignite(config) {
|
|
|
1065
1065
|
return;
|
|
1066
1066
|
}
|
|
1067
1067
|
const duckTyped = err instanceof Error && typeof err.statusCode === "number" ? err : null;
|
|
1068
|
-
if (
|
|
1068
|
+
if (_chunk66R7S7J3cjs.isHttpError.call(void 0, err)) {
|
|
1069
1069
|
const issues = err.issues;
|
|
1070
1070
|
res.status(err.statusCode).json({
|
|
1071
1071
|
error: err.message,
|
|
@@ -1102,7 +1102,7 @@ function gracefulShutdown(server, timeoutMs = 1e4) {
|
|
|
1102
1102
|
server.closeIdleConnections();
|
|
1103
1103
|
server.close(() => {
|
|
1104
1104
|
_chunkYL37D6KMcjs.getLogger.call(void 0, ).info("Server closed");
|
|
1105
|
-
Promise.all([_chunkT4OHFU5Tcjs.closeBullMQ.call(void 0, ), _chunkTYR2GZZEcjs.closePgBoss.call(void 0, ),
|
|
1105
|
+
Promise.all([_chunkT4OHFU5Tcjs.closeBullMQ.call(void 0, ), _chunkTYR2GZZEcjs.closePgBoss.call(void 0, ), _chunk2J3HHQKPcjs.closeCache.call(void 0, )]).catch((err) => _chunkYL37D6KMcjs.getLogger.call(void 0, ).error({ err }, "Task backend close failed")).finally(() => process.exit(0));
|
|
1106
1106
|
});
|
|
1107
1107
|
setTimeout(() => {
|
|
1108
1108
|
_chunkYL37D6KMcjs.getLogger.call(void 0, ).error("Forced exit after timeout");
|
|
@@ -1139,5 +1139,5 @@ function gracefulShutdown(server, timeoutMs = 1e4) {
|
|
|
1139
1139
|
|
|
1140
1140
|
|
|
1141
1141
|
|
|
1142
|
-
exports.HttpError =
|
|
1142
|
+
exports.HttpError = _chunk66R7S7J3cjs.HttpError; exports.ModelValidationError = _chunk66R7S7J3cjs.ModelValidationError; exports.cache = _chunk2J3HHQKPcjs.cache; exports.cacheResponse = cacheResponse; exports.compose = compose; exports.db = _chunkRGTENTDNcjs.db; exports.defineModel = _chunkRGTENTDNcjs.defineModel; exports.defineTable = _chunkRGTENTDNcjs.defineTable; exports.getDbClient = _chunkRGTENTDNcjs.getDbClient; exports.getLogger = _chunkYL37D6KMcjs.getLogger; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.isHttpError = _chunk66R7S7J3cjs.isHttpError; exports.listTasks = _chunkTI24L4XEcjs.listTasks; exports.logger = _chunkYL37D6KMcjs.logger; exports.scanDir = _chunkR34R7QPDcjs.scanDir; exports.setDbClient = _chunkRGTENTDNcjs.setDbClient; exports.transaction = _chunkRGTENTDNcjs.transaction; exports.workerCount = workerCount;
|
|
1143
1143
|
//# sourceMappingURL=index.cjs.map
|