express-file-cluster 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/auth/index.d.cts +1 -1
  2. package/dist/auth/index.d.ts +1 -1
  3. package/dist/{chunk-2PBMLMO4.js → chunk-QKQZF573.js} +26 -4
  4. package/dist/chunk-QKQZF573.js.map +1 -0
  5. package/dist/{chunk-6QNLN6AI.js → chunk-RRQ2RK5M.js} +353 -3
  6. package/dist/chunk-RRQ2RK5M.js.map +1 -0
  7. package/dist/{chunk-RGTENTDN.cjs → chunk-RTF7PHS2.cjs} +432 -82
  8. package/dist/chunk-RTF7PHS2.cjs.map +1 -0
  9. package/dist/{chunk-66R7S7J3.cjs → chunk-X2US4RAM.cjs} +26 -4
  10. package/dist/chunk-X2US4RAM.cjs.map +1 -0
  11. package/dist/cli/db-runner.cjs +17 -17
  12. package/dist/cli/db-runner.js +2 -2
  13. package/dist/cli/index.cjs +363 -26
  14. package/dist/cli/index.cjs.map +1 -1
  15. package/dist/cli/index.js +343 -6
  16. package/dist/cli/index.js.map +1 -1
  17. package/dist/docs/api-reference/collection.md +155 -0
  18. package/dist/docs/cli/add.md +35 -6
  19. package/dist/docs/guides/authentication.md +50 -0
  20. package/dist/docs/guides/coming-from-mongoose.md +60 -0
  21. package/dist/docs/guides/which-api.md +21 -12
  22. package/dist/docs/index.md +3 -1
  23. package/dist/docs/skills/SKILL.md +2 -2
  24. package/dist/docs/skills/api-surface.md +8 -0
  25. package/dist/docs/skills/what-not-to-invent.md +3 -2
  26. package/dist/index.cjs +11 -9
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +193 -3
  29. package/dist/index.d.ts +193 -3
  30. package/dist/index.js +4 -2
  31. package/dist/index.js.map +1 -1
  32. package/dist/registry/index.json +1 -1
  33. package/dist/tasks/index.d.cts +1 -1
  34. package/dist/tasks/index.d.ts +1 -1
  35. package/dist/{types-gyvA7BtO.d.cts → types-BY-ObnZH.d.cts} +36 -7
  36. package/dist/{types-gyvA7BtO.d.ts → types-BY-ObnZH.d.ts} +36 -7
  37. package/package.json +1 -1
  38. package/dist/chunk-2PBMLMO4.js.map +0 -1
  39. package/dist/chunk-66R7S7J3.cjs.map +0 -1
  40. package/dist/chunk-6QNLN6AI.js.map +0 -1
  41. package/dist/chunk-RGTENTDN.cjs.map +0 -1
@@ -0,0 +1,155 @@
1
+ # defineCollection — API Reference
2
+
3
+ `defineCollection` is the MongoDB-native model API. It uses mongoose's vocabulary (`find` with projections, `findOneAndUpdate`, `bulkWrite`, aggregation pipelines, change streams) and adds BSON types. It runs on the same foundation as `defineModel`: schema format, inferred types, validation, auto-sync, `transaction()`, `efc db generate`. Underneath, it is a mongoose model.
4
+
5
+ Building on PostgreSQL? Use [`defineTable`](./table.md). Need one model for both engines? Use [`defineModel`](./db.md). See [Which model API?](../guides/which-api.md).
6
+
7
+ ```ts
8
+ import { defineCollection, type InferRecord } from 'express-file-cluster';
9
+
10
+ export const Place = defineCollection('Place', {
11
+ name: { type: 'string', required: true },
12
+ location: { type: 'geoPoint', index: '2dsphere' },
13
+ price: { type: 'decimal128' }, // '19.99', exact
14
+ visits: { type: 'long', default: 0 }, // bigint
15
+ tags: { type: 'array', of: 'string', default: [] },
16
+ owner: { type: 'objectId', ref: 'User' },
17
+ reviews: [{ rating: { type: 'number', required: true, min: 1, max: 5 }, text: { type: 'string' } }],
18
+ }, { indexes: [{ fields: { name: 'text' } }] });
19
+
20
+ export type Place = InferRecord<typeof Place>;
21
+
22
+ const near = await Place.find(
23
+ { location: { $near: { $geometry: { type: 'Point', coordinates: [85.32, 27.71] }, $maxDistance: 2000 } } },
24
+ { projection: { name: 1 }, limit: 10 },
25
+ );
26
+ await Place.findOneAndUpdate({ name }, { $inc: { visits: 1 } }, { upsert: true, returnDocument: 'after' });
27
+ ```
28
+
29
+ Using a `defineCollection` model on a PostgreSQL connection fails at its first query, with an `[EFC]` error naming the model.
30
+
31
+ ---
32
+
33
+ ## Field types
34
+
35
+ Every `defineModel` field type and option works (`string`, `number`, `boolean`, `date`, `objectId`, embedded objects and arrays, `required`, `default`, `enum`, `min`/`max`, `match`, `validate`, `ref`, `sequence`, `renamedFrom`). On top of them:
36
+
37
+ | Type | Stored as | In records |
38
+ |---|---|---|
39
+ | `decimal128` | `Decimal128` | `string` (exact, `'19.99'`); writes take strings or numbers |
40
+ | `long` | `Long` (int64) | `bigint`, whatever the size; writes take bigints or numbers |
41
+ | `geoPoint` | GeoJSON `{ type: 'Point', coordinates: [lng, lat] }` | `GeoPoint`; longitude first, both checked for range |
42
+ | `binary` | `Binary` | `Buffer` |
43
+
44
+ The PostgreSQL types (`integer`, `bigint`, `decimal`, `uuid`, `json`) and `defineTable` options are refused at definition, with an `[EFC]` error naming the field.
45
+
46
+ `index` takes `true`, or a special index: `'2dsphere'` (geo), `'text'` or `'hashed'`. In `options.indexes`, field values can also be `'2dsphere'` and `'hashed'`, and an index can be partial:
47
+
48
+ ```ts
49
+ { indexes: [
50
+ { fields: { name: 'text', description: 'text' } },
51
+ { fields: { email: 1 }, unique: true, partialFilterExpression: { deletedAt: { $exists: false } } },
52
+ { fields: { expiresAt: 1 }, expireAfterSeconds: 0 }, // TTL
53
+ ] }
54
+ ```
55
+
56
+ ## Options
57
+
58
+ `ModelOptions` (`timestamps`, `indexes`, `collection`) plus:
59
+
60
+ | Option | |
61
+ |---|---|
62
+ | `collation` | default collation for queries and aggregations, e.g. `{ locale: 'en', strength: 2 }` (case-insensitive) |
63
+
64
+ ---
65
+
66
+ ## Reading
67
+
68
+ ```ts
69
+ find(filter?, options?): Promise<Record[]>
70
+ findOne(filter?, options?): Promise<Record | null>
71
+ findById(id, options?): Promise<Record | null> // malformed id → null
72
+ exists(filter): Promise<boolean>
73
+ countDocuments(filter?): Promise<number>
74
+ estimatedDocumentCount(): Promise<number> // from metadata: fast, no filter
75
+ distinct(field, filter?): Promise<value[]> // arrays are unwound, as in MongoDB
76
+ ```
77
+
78
+ | `options` | |
79
+ |---|---|
80
+ | `projection` | `{ name: 1 }` (only these, plus `id`) or `{ secret: 0 }` (all but these) |
81
+ | `sort` | `{ createdAt: -1, name: 'asc' }`, or `{ score: { $meta: 'textScore' } }` |
82
+ | `skip`, `limit` | |
83
+ | `populate` | `ref` fields to replace with the referenced documents |
84
+ | `collation` | overrides the model's |
85
+
86
+ Filters are MongoDB query documents: every query operator works (`$near`, `$geoWithin`, `$text`, `$elemMatch`, `$regex`, `$expr`, …), as do dotted paths. `id` is accepted for `_id`. Field values are type-checked against the record; dotted paths and operators are not.
87
+
88
+ ## Writing
89
+
90
+ ```ts
91
+ create(data): Promise<Record>
92
+ insertMany(data[]): Promise<Record[]>
93
+ updateOne(filter, update, { upsert? }): Promise<WriteResult>
94
+ updateMany(filter, update, { upsert? }): Promise<WriteResult>
95
+ replaceOne(filter, replacement, { upsert? }): Promise<WriteResult>
96
+ findOneAndUpdate(filter, update, { upsert?, returnDocument?, projection?, sort? }): Promise<Record | null>
97
+ findByIdAndUpdate(id, update, { returnDocument? }): Promise<Record | null>
98
+ findOneAndDelete(filter, { sort? }): Promise<Record | null>
99
+ findByIdAndDelete(id): Promise<Record | null>
100
+ deleteOne(filter): Promise<{ deletedCount }>
101
+ deleteMany(filter?): Promise<{ deletedCount }>
102
+ bulkWrite(ops, { ordered? }): Promise<BulkResult>
103
+ ```
104
+
105
+ - `WriteResult` is `{ matchedCount, modifiedCount, upsertedCount, upsertedId }`.
106
+ - As in mongoose, `findOneAndUpdate` returns the document **before** the update unless you pass `returnDocument: 'after'`.
107
+ - Updates take plain fields (shorthand for `$set`) or any update operator (`$set $unset $inc $mul $min $max $push $pull $addToSet $pop $rename $setOnInsert $currentDate`).
108
+ - **Writes are validated**: creates against the whole schema, updates on the fields they change (`runValidators`). Failures throw `ModelValidationError` (400 with `issues`). A duplicate on a unique index is an `HttpError` 409.
109
+ - `bulkWrite` takes `insertOne`, `updateOne`, `updateMany`, `replaceOne`, `deleteOne` and `deleteMany` operations, and returns `{ insertedCount, matchedCount, modifiedCount, deletedCount, upsertedCount }`.
110
+
111
+ ```ts
112
+ await Place.bulkWrite([
113
+ { insertOne: { document: { name: 'Patan' } } },
114
+ { updateOne: { filter: { name: 'Boudha' }, update: { $addToSet: { tags: 'stupa' } }, upsert: true } },
115
+ { deleteMany: { filter: { visits: { $lt: 1 } } } },
116
+ ]);
117
+ ```
118
+
119
+ ## Aggregation
120
+
121
+ ```ts
122
+ const ratings = await Place.aggregate<{ _id: string; avg: number }>([
123
+ { $unwind: '$reviews' },
124
+ { $group: { _id: '$name', avg: { $avg: '$reviews.rating' } } },
125
+ { $sort: { avg: -1 } },
126
+ ]);
127
+ ```
128
+
129
+ The pipeline is passed to MongoDB unchanged; type the output with the generic. Results get the same conversions as records: decimals become strings, longs bigints, `_id` gains a string `id`. `$lookup` joins other collections by collection name.
130
+
131
+ ## Change streams
132
+
133
+ ```ts
134
+ const stream = Place.watch([{ $match: { operationType: 'insert' } }]);
135
+ for await (const change of stream) {
136
+ console.log(change.operationType, change.id, change.fullDocument?.name);
137
+ if (done) break; // or: await stream.close()
138
+ }
139
+ ```
140
+
141
+ Each change has `operationType`, `id` (the document's), `fullDocument` (inserts and replaces; updates with `{ fullDocument: 'updateLookup' }`), `updateDescription` and `raw` (the driver's event). Change streams need a replica set.
142
+
143
+ ## Transactions
144
+
145
+ Calls inside `transaction(async () => { … })` join it, as with `defineModel`. MongoDB transactions need a replica set.
146
+
147
+ ## Sync and migrations
148
+
149
+ The same as `defineModel` on MongoDB. On first use the collection and its indexes are created (`autoSync`). `efc db sync [--dry-run]` reconciles indexes, and `efc db generate` writes migrations for index changes and `renamedFrom` fields.
150
+
151
+ ## Also
152
+
153
+ - `raw()`: the mongoose `Model`, for anything not covered here.
154
+ - `sync({ dryRun? })`, `drop()`.
155
+ - Types: `InferRecord<typeof Place>`, `InferCreate<typeof Place>`, `CollectionFilter<R>`, `CollectionUpdate<R>`.
@@ -34,6 +34,7 @@ efc diff # compare installed features with the regi
34
34
  | `--overwrite` | Replace files you've changed with the registry version |
35
35
  | `--no-install` | Don't run `npm install` / `pnpm install` / … afterwards |
36
36
  | `--no-prompt` | Don't ask the items' questions — write placeholders to `.env` instead |
37
+ | `--entity <name>` | Scaffold a custom authenticatable entity (model + namespaced auth routes) |
37
38
 
38
39
  ---
39
40
 
@@ -66,13 +67,41 @@ efc diff # compare installed features with the regi
66
67
 
67
68
  The full route list is in [Generated Portals](../guides/generated-portals.md); OAuth setup is in [Sign in with Google & Apple](../guides/oauth.md).
68
69
 
69
- A few things hold for every item:
70
+ ---
71
+
72
+ ## Custom auth entities
73
+
74
+ While `efc add auth` scaffolds the standard **User** and **Admin** principals, real-world apps (marketplaces, food delivery, logistics) often need custom entities like `Merchant`, `Driver`, `Seller`, or `DeliveryPartner`.
75
+
76
+ EFC provides a first-class shortcut to scaffold an authenticatable entity with its own model and namespaced routes:
77
+
78
+ ```bash
79
+ # Any of these syntaxes work:
80
+ efc add auth --entity merchant
81
+ efc add auth:merchant
82
+ efc add auth new merchant
83
+
84
+ # Multiple entities at once:
85
+ efc add auth:merchant auth:delivery-partner
86
+ ```
87
+
88
+ ### What gets generated
89
+
90
+ For `efc add auth:merchant`:
91
+
92
+ | File | Purpose |
93
+ |---|---|
94
+ | `src/model/Merchant.ts` | Model with `name`, `email`, `password`, `role: 'merchant'`, `isActive`, tokens |
95
+ | `src/api/auth/merchant/register.ts` | `POST /auth/merchant/register` |
96
+ | `src/api/auth/merchant/login.ts` | `POST /auth/merchant/login` (issues token with `role: 'merchant'`) |
97
+ | `src/api/auth/merchant/logout.ts` | `POST /auth/merchant/logout` |
98
+ | `src/api/auth/merchant/me.ts` | `GET /auth/merchant/me` (guarded by `requireAuth('merchant')`) |
99
+
100
+ - **No existing routes modified:** Existing `/auth/login` and `/auth/register` remain untouched.
101
+ - **Model registered:** On PostgreSQL with `defineTable`, registers the model in `src/model/index.ts`.
102
+ - **Packages ensured:** Adds `bcrypt` (and `@types/bcrypt` in TypeScript) to `package.json` and runs package manager install if missing.
103
+ - **Tracked in efc.json:** Recorded as `auth:<slug>` in `efc.json`.
70
104
 
71
- - **Dependencies come along.** `efc add admin-users` also installs `auth` and `admin` if they're missing.
72
- - **Routes that send email** (`auth`, `forgot-password`, `email-verification`) enqueue the `SendEmail` task. The base app has a stub that logs the message. `efc add email-client` swaps in real SMTP. These items need a task backend (`tasks` in `efc.config`); the base app always has one.
73
- - **Models shared by two items** (`Plan`, `SupportTicket`, `Notification`) are identical in both. The second item skips the file that's already there.
74
- - **On PostgreSQL with `defineTable`**, references are real foreign keys, and `efc add` registers new models in `src/model/index.ts` (the export plus the `Tables` entry). Models declare no back-relations. Add `relations: { … }` to a model when you want `include`. See [defineTable](../api-reference/table.md).
75
- - **Tables and collections** are created on first use (`autoSync`). With `autoSync: false`, run `efc db sync` or write a migration.
76
105
 
77
106
  ---
78
107
 
@@ -187,6 +187,55 @@ and pass it through as `cookieDomain: process.env.COOKIE_DOMAIN` in `efc.config.
187
187
 
188
188
  ---
189
189
 
190
+ ## Custom auth entities
191
+
192
+ EFC ships with **User** and **Admin** as built-in principals (`efc add auth`). Many apps need additional authenticatable entities — a food delivery app might have `Merchant` and `DeliveryPartner`, a marketplace might have `Seller` and `Buyer`.
193
+
194
+ Use `efc add auth:` to scaffold a new entity with its own model and namespaced auth routes:
195
+
196
+ ```bash
197
+ # Either syntax works:
198
+ efc add auth:merchant
199
+ efc add auth --entity merchant
200
+
201
+ # Multiple at once:
202
+ efc add auth:merchant auth:driver
203
+ ```
204
+
205
+ ### What gets generated
206
+
207
+ For `efc add auth:merchant`:
208
+
209
+ | File | Purpose |
210
+ |---|---|
211
+ | `src/model/Merchant.ts` | Model with name, email, password, role, isActive, tokens |
212
+ | `src/api/auth/merchant/register.ts` | `POST /auth/merchant/register` |
213
+ | `src/api/auth/merchant/login.ts` | `POST /auth/merchant/login` |
214
+ | `src/api/auth/merchant/logout.ts` | `POST /auth/merchant/logout` |
215
+ | `src/api/auth/merchant/me.ts` | `GET /auth/merchant/me` |
216
+
217
+ The generated code uses the same auth primitives (`issueToken`, `requireAuth`, `revokeSession`) as the built-in User/Admin. Each entity's JWT carries `role: 'merchant'` (or whatever the entity name is, lowercased).
218
+
219
+ ### Protecting routes by entity
220
+
221
+ ```ts
222
+ import { requireAuth } from 'express-file-cluster/auth';
223
+
224
+ // Only merchants can access this route:
225
+ export const middlewares = [requireAuth('merchant')];
226
+
227
+ // Merchants OR admins:
228
+ export const middlewares = [requireAuth('merchant', 'admin')];
229
+ ```
230
+
231
+ ### Customising the generated code
232
+
233
+ The files belong to you — they're copied into your `src/` just like `efc add auth`. Add fields to the model, change the registration flow, add email verification — it's your code.
234
+
235
+ > **Note:** The existing `/auth/login` and `/auth/register` routes are **not modified**. Each custom entity gets its own namespace (`/auth/<entity>/...`), so nothing breaks.
236
+
237
+ ---
238
+
190
239
  ## Environment variables
191
240
 
192
241
  | Variable | Wired into (via `efc.config.ts`) | Description |
@@ -196,3 +245,4 @@ and pass it through as `cookieDomain: process.env.COOKIE_DOMAIN` in `efc.config.
196
245
  | `COOKIE_DOMAIN` | `cookieDomain` | Cookie domain for `http-only` strategy |
197
246
 
198
247
  `ignite()` doesn't read any of these from `process.env` itself — see the full [Environment Variables reference](./environment-variables.md) for how the scaffolded `efc.config.ts` wires them.
248
+
@@ -0,0 +1,60 @@
1
+ # Coming from mongoose
2
+
3
+ `defineCollection` keeps mongoose's query language, with the schema as a plain object, types inferred from it, and validation errors that become HTTP responses. Underneath it is still mongoose, so your data and indexes stay as they are.
4
+
5
+ ---
6
+
7
+ ## 1. Schemas
8
+
9
+ ```ts
10
+ // mongoose
11
+ const PlaceSchema = new Schema({
12
+ name: { type: String, required: true },
13
+ price: Schema.Types.Decimal128,
14
+ location: { type: { type: String, enum: ['Point'] }, coordinates: [Number] },
15
+ owner: { type: Schema.Types.ObjectId, ref: 'User' },
16
+ }, { timestamps: true });
17
+ PlaceSchema.index({ location: '2dsphere' });
18
+ export const Place = model('Place', PlaceSchema);
19
+
20
+ // EFC
21
+ export const Place = defineCollection('Place', {
22
+ name: { type: 'string', required: true },
23
+ price: { type: 'decimal128' },
24
+ location: { type: 'geoPoint', index: '2dsphere' },
25
+ owner: { type: 'objectId', ref: 'User' },
26
+ });
27
+ export type Place = InferRecord<typeof Place>; // no interface to keep in step
28
+ ```
29
+
30
+ | mongoose | EFC |
31
+ |---|---|
32
+ | `String`, `Number`, `Boolean`, `Date`, `ObjectId` | `'string'`, `'number'`, `'boolean'`, `'date'`, `'objectId'` |
33
+ | `Decimal128`, `BigInt`, `Buffer` | `'decimal128'` (string), `'long'` (bigint), `'binary'` (Buffer) |
34
+ | GeoJSON point sub-schema | `'geoPoint'` |
35
+ | `[String]`, `[SubSchema]` | `{ type: 'array', of: 'string' }`, `[{ … }]` |
36
+ | `required`, `default`, `enum`, `min`, `max`, `minlength`, `match`, `validate` | same names (`minLength`, `maxLength`) |
37
+ | `timestamps: true` | the default |
38
+ | `schema.index({...})` | `index:` on the field, or `options.indexes` |
39
+
40
+ ## 2. Queries
41
+
42
+ | mongoose | EFC |
43
+ |---|---|
44
+ | `Model.find(filter).select('name').sort('-createdAt').limit(10).lean()` | `Place.find(filter, { projection: { name: 1 }, sort: { createdAt: -1 }, limit: 10 })` |
45
+ | `.populate('owner')` | `{ populate: 'owner' }` |
46
+ | `findOne`, `findById`, `countDocuments`, `distinct`, `exists` | same names |
47
+ | `create`, `insertMany`, `updateOne`, `updateMany`, `replaceOne`, `deleteOne`, `deleteMany` | same names and result counts |
48
+ | `findOneAndUpdate(f, u, { new: true, upsert: true })` | `findOneAndUpdate(f, u, { returnDocument: 'after', upsert: true })` |
49
+ | `aggregate([...])`, `bulkWrite([...])`, `watch([...])` | same |
50
+ | `session` passed to every call | `transaction(async () => { … })` and calls inside join it |
51
+
52
+ Records are plain objects (like `lean()`) with a string `id`. Decimals come back as strings and longs as bigints.
53
+
54
+ ## 3. What you gain
55
+
56
+ - Validation errors become a **400** with `issues`, and duplicate keys a **409**, with no error-handling code.
57
+ - Collections and indexes are created on first use (`autoSync`), and `efc db generate` writes index migrations.
58
+ - Need one model for MongoDB and PostgreSQL? Use [`defineModel`](../api-reference/db.md) instead. See [Which model API?](./which-api.md).
59
+
60
+ Full reference: [`defineCollection`](../api-reference/collection.md).
@@ -1,24 +1,24 @@
1
1
  # Which model API?
2
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.
3
+ EFC has three 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
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 |
5
+ | | `defineModel` | `defineTable` | `defineCollection` |
6
+ |---|---|---|---|
7
+ | Engine | MongoDB or PostgreSQL (set by `DATABASE_URL`) | PostgreSQL only | MongoDB only |
8
+ | Queries | portable subset: `find(filter, { sort, limit, populate })`, `$set`, `$inc` | Prisma-style: `findMany({ where, include, orderBy, take, cursor })`, `findUnique`, `upsert`, `groupBy`, `aggregate` | mongoose-style: every query operator, `find(filter, { projection })`, `findOneAndUpdate`, `bulkWrite`, `aggregate(pipeline)`, `watch` |
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 | `ref` + `populate`, `$lookup`, embedded documents |
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 | + `decimal128`, `long`, `geoPoint`, `binary`; `2dsphere`, `text`, `hashed` and partial indexes |
11
+ | Migrations | auto-sync, `efc db generate` | auto-sync, `efc db generate`, `efc db pull`, `efc import-prisma` | auto-sync, `efc db generate` |
12
+ | Wrong engine | — | fails at first use with an `[EFC]` error naming the model | the same |
13
13
 
14
14
  ## Pick one
15
15
 
16
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.
17
+ - **Building on MongoDB:** use `defineCollection`. You get the full query language, geo and text search, BSON types, `bulkWrite` and change streams. It is mongoose underneath (`raw()` hands you the mongoose model).
18
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
19
  - **Coming from Prisma:** use `defineTable`. `efc import-prisma` writes the models for you. See [Coming from Prisma](./coming-from-prisma.md).
20
20
 
21
- ## The same query, both ways
21
+ ## The same query, three ways
22
22
 
23
23
  ```ts
24
24
  // defineModel
@@ -36,10 +36,19 @@ const posts = await Post.findMany({
36
36
  include: { author: true },
37
37
  });
38
38
  await Post.update({ where: { id }, data: { views: { increment: 1 } } });
39
+
40
+ // defineCollection
41
+ const posts = await Post.find(
42
+ { status: 'published', views: { $gte: 100 } },
43
+ { sort: { createdAt: -1 }, limit: 20, populate: 'author', projection: { body: 0 } },
44
+ );
45
+ await Post.findByIdAndUpdate(id, { $inc: { views: 1 } });
39
46
  ```
40
47
 
41
48
  ## Moving between them
42
49
 
50
+ On MongoDB, `defineModel` and `defineCollection` over the same collection read and write the same documents. Only the method names and results differ (`updateMany` returns `{ modifiedCount, … }` instead of a number, for example).
51
+
43
52
  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
53
 
45
54
  - 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.
@@ -47,4 +56,4 @@ On PostgreSQL, a `defineModel` and a `defineTable` over the same table read and
47
56
 
48
57
  Run `efc db sync --dry-run` before you switch to see exactly what will change.
49
58
 
50
- See also: [Database guide](./database.md) · [Relations](./relations.md) · [`defineModel` API](../api-reference/db.md) · [`defineTable` API](../api-reference/table.md)
59
+ See also: [Database guide](./database.md) · [Relations](./relations.md) · [`defineModel` API](../api-reference/db.md) · [`defineTable` API](../api-reference/table.md) · [`defineCollection` API](../api-reference/collection.md)
@@ -37,11 +37,13 @@
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 |
40
+ | [Which model API?](./guides/which-api.md) | `defineModel` vs `defineTable` vs `defineCollection`, and moving between them |
41
41
  | [Relations](./guides/relations.md) | Foreign keys, many-to-many, `include`, relation filters, nested writes |
42
42
  | [defineTable](./api-reference/table.md) | PostgreSQL-native models: Prisma-style queries, SQL types, aggregation |
43
+ | [defineCollection](./api-reference/collection.md) | MongoDB-native models: mongoose-style queries, BSON types, geo, bulk writes, change streams |
43
44
  | [Migrations & Seeds](./guides/migrations.md) | `efc db generate / migrate / rollback / pull / seed / studio`, drift checks |
44
45
  | [Coming from Prisma](./guides/coming-from-prisma.md) | `efc import-prisma`, schema and query mapping |
46
+ | [Coming from mongoose](./guides/coming-from-mongoose.md) | `defineCollection` for mongoose users: schema and query mapping |
45
47
  | [Validation](./guides/validation.md) | Route `schema` exports with zod, valibot, arktype |
46
48
  | [Logging](./guides/logging.md) | pino, request IDs, `getLogger()` |
47
49
  | [Caching & Sessions](./guides/caching.md) | `cache`, `cacheResponse`, revoking JWT sessions |
@@ -39,6 +39,6 @@ Load **only** the module the work points to. Each is self-contained.
39
39
 
40
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`) incl. migrations generated from model diffs (`efc db generate`), `efc db pull` and `efc import-prisma`, 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), MongoDB-native `defineCollection` (mongoose vocabulary, BSON types, geo/text, `bulkWrite`, change streams), 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`, `defineCollection`.
44
+ **Not yet implemented (Phase 3+):** WebSockets, plugins, OpenAPI generation, OpenTelemetry, `efc lint`, `efc deploy`.
@@ -35,6 +35,14 @@ function defineModel(name: string, schema: ModelSchema, options?: ModelOptions):
35
35
  type InferRecord<typeof Model> // record incl. id + timestamps per options (defineModel and defineTable)
36
36
  type InferCreate<typeof Model> // create() input: required w/o default/sequence mandatory; dates accept string|number
37
37
  async function transaction<T>(fn: () => Promise<T>): Promise<T> // model calls inside join automatically
38
+ // MongoDB-native (mongoose vocabulary + BSON types); PostgreSQL → [EFC] error at first use
39
+ function defineCollection(name: string, schema: CollectionSchema, options?: CollectionOptions): CollectionModel<S, O>
40
+ // types: + 'decimal128' (string) 'long' (bigint) 'geoPoint' ({ type: 'Point', coordinates: [lng, lat] }) 'binary' (Buffer)
41
+ // index: true | '2dsphere' | 'text' | 'hashed'; options.indexes + partialFilterExpression; options.collation
42
+ // find(filter, { projection, sort, skip, limit, populate, collation }) · findOne · findById · exists · countDocuments · distinct
43
+ // create · insertMany · updateOne/updateMany/replaceOne(f, u, { upsert }) → { matchedCount, modifiedCount, upsertedCount, upsertedId }
44
+ // findOneAndUpdate(f, u, { upsert, returnDocument: 'before' (default) | 'after' }) · findByIdAndUpdate · findOneAndDelete · findByIdAndDelete
45
+ // deleteOne/deleteMany → { deletedCount } · bulkWrite(ops) · aggregate<T>(pipeline) · watch(pipeline) (replica set; for await)
38
46
  // PostgreSQL-native (Prisma vocabulary + SQL types); MongoDB → [EFC] error at first use
39
47
  function defineTable(name: string, schema: TableSchema, options?: TableOptions): TableModel<S, O>
40
48
  // types: + 'integer' (number) 'bigint' (bigint) 'decimal' {precision, scale} (string, exact) 'uuid' 'json'
@@ -36,7 +36,8 @@ defineMiddleware()
36
36
  defineModel() // ← WAIT — this DOES exist, from main path
37
37
  createModel() // ← does NOT exist (it's defineModel, not createModel)
38
38
  defineTable() // ← EXISTS (PostgreSQL-only, Prisma-style) — see api-surface.md
39
- defineCollection() // ← NOT YET — planned (MongoDB-native API, prisma-parity-plan M5)
39
+ defineCollection() // ← EXISTS (MongoDB-only, mongoose vocabulary) — see api-surface.md
40
+ Collection.findMany() / include // ← defineTable vocabulary, NOT on defineCollection
40
41
  Model.findMany() / findUnique() / groupBy() // ← only on defineTable, NOT on defineModel
41
42
  Table.find() / findById() / $gt / $inc // ← defineModel vocabulary, NOT on defineTable
42
43
  Table.findMany({ include }) // ← EXISTS; so do relation filters `{ posts: { some } }` and nested writes `{ connect }` (defineTable only)
@@ -140,7 +141,7 @@ efc remove <item> # NOT IMPLEMENTED — `efc add` copies files; delete them yo
140
141
  efc add <url|@ns/x> # NOT IMPLEMENTED — only the built-in registry (efc list); no third-party registries
141
142
  ```
142
143
 
143
- `efc add | list | view | diff | init` DO exist (the feature registry, `docs/cli/add.md`).
144
+ `efc add | list | view | diff | init` DO exist (the feature registry, `docs/cli/add.md`). Custom auth entities can be scaffolded via `efc add auth --entity <name>`, `efc add auth:<name>`, or `efc add auth new <name>` (e.g. `efc add auth:merchant`).
144
145
  OAuth sign-in exists only as registry items (`efc add auth@google`, `efc add auth@apple`) —
145
146
  app code in `src/api/auth/<provider>/` + `src/lib/oauth`; there is NO framework OAuth API
146
147
  (no `passport`, no `oauth` option on `ignite()`, no other providers).
package/dist/index.cjs CHANGED
@@ -20,14 +20,15 @@ var _chunkT4OHFU5Tcjs = require('./chunk-T4OHFU5T.cjs');
20
20
 
21
21
 
22
22
 
23
- var _chunkRGTENTDNcjs = require('./chunk-RGTENTDN.cjs');
24
23
 
24
+ var _chunkRTF7PHS2cjs = require('./chunk-RTF7PHS2.cjs');
25
25
 
26
26
 
27
27
 
28
28
 
29
29
 
30
- var _chunk66R7S7J3cjs = require('./chunk-66R7S7J3.cjs');
30
+
31
+ var _chunkX2US4RAMcjs = require('./chunk-X2US4RAM.cjs');
31
32
 
32
33
 
33
34
 
@@ -997,14 +998,14 @@ async function ignite(config) {
997
998
  for (const mw of globalMiddlewares) {
998
999
  app.use(mw);
999
1000
  }
1000
- if (database) _chunk66R7S7J3cjs.setDbEngine.call(void 0, database);
1001
- _chunk66R7S7J3cjs.setAutoSync.call(void 0, _nullishCoalesce(config.autoSync, () => ( true)));
1001
+ if (database) _chunkX2US4RAMcjs.setDbEngine.call(void 0, database);
1002
+ _chunkX2US4RAMcjs.setAutoSync.call(void 0, _nullishCoalesce(config.autoSync, () => ( true)));
1002
1003
  if (database === "mongodb" && databaseUrl) {
1003
- const conn = await _chunkRGTENTDNcjs.connectMongo.call(void 0, databaseUrl, config.databasePool);
1004
- _chunkRGTENTDNcjs.setDbClient.call(void 0, conn);
1004
+ const conn = await _chunkRTF7PHS2cjs.connectMongo.call(void 0, databaseUrl, config.databasePool);
1005
+ _chunkRTF7PHS2cjs.setDbClient.call(void 0, conn);
1005
1006
  } else if (database === "postgresql" && databaseUrl) {
1006
1007
  const pool = await _chunkVQSWSYK6cjs.connectPostgres.call(void 0, databaseUrl, config.databasePool);
1007
- _chunkRGTENTDNcjs.setDbClient.call(void 0, pool);
1008
+ _chunkRTF7PHS2cjs.setDbClient.call(void 0, pool);
1008
1009
  }
1009
1010
  if (config.cache) {
1010
1011
  await _chunk2J3HHQKPcjs.configureCache.call(void 0, config.cache);
@@ -1065,7 +1066,7 @@ async function ignite(config) {
1065
1066
  return;
1066
1067
  }
1067
1068
  const duckTyped = err instanceof Error && typeof err.statusCode === "number" ? err : null;
1068
- if (_chunk66R7S7J3cjs.isHttpError.call(void 0, err)) {
1069
+ if (_chunkX2US4RAMcjs.isHttpError.call(void 0, err)) {
1069
1070
  const issues = err.issues;
1070
1071
  res.status(err.statusCode).json({
1071
1072
  error: err.message,
@@ -1139,5 +1140,6 @@ function gracefulShutdown(server, timeoutMs = 1e4) {
1139
1140
 
1140
1141
 
1141
1142
 
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
+
1144
+ exports.HttpError = _chunkX2US4RAMcjs.HttpError; exports.ModelValidationError = _chunkX2US4RAMcjs.ModelValidationError; exports.cache = _chunk2J3HHQKPcjs.cache; exports.cacheResponse = cacheResponse; exports.compose = compose; exports.db = _chunkRTF7PHS2cjs.db; exports.defineCollection = _chunkRTF7PHS2cjs.defineCollection; exports.defineModel = _chunkRTF7PHS2cjs.defineModel; exports.defineTable = _chunkRTF7PHS2cjs.defineTable; exports.getDbClient = _chunkRTF7PHS2cjs.getDbClient; exports.getLogger = _chunkYL37D6KMcjs.getLogger; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.isHttpError = _chunkX2US4RAMcjs.isHttpError; exports.listTasks = _chunkTI24L4XEcjs.listTasks; exports.logger = _chunkYL37D6KMcjs.logger; exports.scanDir = _chunkR34R7QPDcjs.scanDir; exports.setDbClient = _chunkRTF7PHS2cjs.setDbClient; exports.transaction = _chunkRTF7PHS2cjs.transaction; exports.workerCount = workerCount;
1143
1145
  //# sourceMappingURL=index.cjs.map