@aaroncadillac/crudify-mongo 1.8.0 → 3.0.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/CHANGELOG.md +112 -0
- package/README.md +256 -202
- package/crudify.js +310 -182
- package/package.json +47 -8
- package/sanitizer.js +264 -0
- package/.github/workflows/publish.yml +0 -34
- package/.github/workflows/test.yml +0 -21
- package/example/db-connection.js +0 -15
- package/example/models/posts.js +0 -30
- package/example/models/users.js +0 -37
- package/example/routes.js +0 -15
- package/example/server.js +0 -20
- package/jest-mongodb-config.js +0 -11
- package/jest.config.js +0 -7
- package/test/crudify.test.js +0 -73
package/README.md
CHANGED
|
@@ -2,280 +2,334 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://opensource.org/licenses/MPL-2.0)
|
|
4
4
|

|
|
5
|
+

|
|
6
|
+

|
|
5
7
|

|
|
6
8
|
|
|
9
|
+
A CRUD generator for [Fastify](https://fastify.dev) and [Mongoose](https://mongoosejs.com) that is **safe to expose by default**: client queries are sanitized, results are bounded, errors never leak internals, and every read and write can be pinned to a server-side scope. It is small (two files, no runtime dependencies) and extensible through hooks and custom routes.
|
|
7
10
|
|
|
8
|
-
|
|
11
|
+
> Upgrading from 1.x? Read the [migration guide](CHANGELOG.md#migration-guide-1x--20).
|
|
9
12
|
|
|
10
|
-
|
|
13
|
+
- [Install](#install)
|
|
14
|
+
- [Quick start](#quick-start)
|
|
15
|
+
- [Secure by default](#secure-by-default)
|
|
16
|
+
- [Authentication and authorization](#authentication-and-authorization)
|
|
17
|
+
- [Query language](#query-language)
|
|
18
|
+
- [Options](#options)
|
|
19
|
+
- [Errors](#errors)
|
|
20
|
+
- [Scope and authorize](#scope-and-authorize)
|
|
21
|
+
- [Hooks and request order](#hooks-and-request-order)
|
|
22
|
+
- [Custom routes, actions and overrides](#custom-routes-actions-and-overrides)
|
|
23
|
+
- [Recipes](#recipes)
|
|
24
|
+
- [The sanitizer on its own](#the-sanitizer-on-its-own)
|
|
25
|
+
- [JSON Schema and Swagger](#json-schema-and-swagger)
|
|
26
|
+
- [Performance](#performance)
|
|
11
27
|
|
|
12
|
-
|
|
13
|
-
- [Automatic CRUD generation](#automatic-crud-generation)
|
|
14
|
-
- [Custom routes](#custom-routes)
|
|
15
|
-
- [Getting started](#getting-started)
|
|
16
|
-
- [Installation](#installation)
|
|
17
|
-
- [Usage](#usage)
|
|
18
|
-
- [Aknowledgements](#aknowledgements)
|
|
19
|
-
- [License](#license)
|
|
28
|
+
## Install
|
|
20
29
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
- [Fastify](https://fastify.dev) v4 or higher
|
|
24
|
-
- [Mongoose](https://mongoosejs.com) v8 or higher
|
|
25
|
-
- [mongoose-paginate-v2](https://www.npmjs.com/package/mongoose-paginate-v2) v1.8 or higher
|
|
26
|
-
|
|
27
|
-
## Features
|
|
28
|
-
|
|
29
|
-
### Automatic CRUD generation
|
|
30
|
-
|
|
31
|
-
You can automatically enjoy the following CRUD operations:
|
|
32
|
-
|
|
33
|
-
| Route | Description | Additional built-in benefits |
|
|
34
|
-
|-------|-------------|----|
|
|
35
|
-
| `GET /` | Get all documents | `Pagination` `Filtering` `Sorting` |
|
|
36
|
-
| `GET /:id` | Get a document by id | `Not-Found validation`|
|
|
37
|
-
| `POST /` | Create a document | `Schema validation`|
|
|
38
|
-
| `PUT /:id` | Update a document by id | `Not-Found validation` `Schema validation`|
|
|
39
|
-
| `DELETE /:id` | Delete a document by id | `Not-Found validation` |
|
|
40
|
-
|
|
41
|
-
### Custom routes
|
|
42
|
-
|
|
43
|
-
You can add custom routes to the CRUD, to increase the functionality of your API, you only need to pass the route configuration to the plugin.
|
|
44
|
-
|
|
45
|
-
```js
|
|
46
|
-
const routes = ( fastify, opts, done ) => {
|
|
47
|
-
fastify.register(Crudify, {
|
|
48
|
-
url: '/users',
|
|
49
|
-
Model: UserModel,
|
|
50
|
-
additionalRoutes: [
|
|
51
|
-
{
|
|
52
|
-
method: 'GET',
|
|
53
|
-
url: '/:id/light-details',
|
|
54
|
-
handler: LightDetailsUserHandler
|
|
55
|
-
},
|
|
56
|
-
...
|
|
57
|
-
]
|
|
58
|
-
})
|
|
30
|
+
```bash
|
|
31
|
+
yarn add @aaroncadillac/crudify-mongo
|
|
59
32
|
```
|
|
60
33
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
You can add Swagger auto-documentation to your API, using the [`@fastify/swagger`](https://github.com/fastify/fastify-swagger) and [`@fastify/swagger-ui`](https://github.com/fastify/fastify-swagger-ui) plugins.
|
|
34
|
+
Requires Node >= 20 (Node 22, the current LTS, is recommended), Fastify 4 or 5, Mongoose 8 and, for the list route, [mongoose-paginate-v2](https://www.npmjs.com/package/mongoose-paginate-v2) >= 1.8. They are peer dependencies: Crudify imports none of them.
|
|
64
35
|
|
|
65
|
-
|
|
36
|
+
## Quick start
|
|
66
37
|
|
|
67
38
|
```js
|
|
68
|
-
// server.js
|
|
69
|
-
|
|
70
|
-
import 'dotenv/config';
|
|
71
39
|
import Fastify from 'fastify'
|
|
72
|
-
import
|
|
73
|
-
import
|
|
74
|
-
import
|
|
75
|
-
import * as SwaggerUI from '@fastify/swagger-ui'
|
|
40
|
+
import mongoose from 'mongoose'
|
|
41
|
+
import paginate from 'mongoose-paginate-v2'
|
|
42
|
+
import { Crudify } from '@aaroncadillac/crudify-mongo'
|
|
76
43
|
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
}
|
|
44
|
+
const userSchema = new mongoose.Schema({
|
|
45
|
+
name: { type: String, required: true },
|
|
46
|
+
email: { type: String, required: true }
|
|
47
|
+
}, { timestamps: true })
|
|
48
|
+
userSchema.plugin(paginate) // required by the list route
|
|
80
49
|
|
|
81
|
-
|
|
82
|
-
process.env.NODE_ENV == 'development' && fastify.register(Swagger) && await fastify.register(SwaggerUI, {
|
|
83
|
-
routePrefix: '/docs',
|
|
84
|
-
uiConfig: {
|
|
85
|
-
docExpansion: 'list',
|
|
86
|
-
deepLinking: true
|
|
87
|
-
},
|
|
88
|
-
uiHooks: {
|
|
89
|
-
onRequest: function (request, reply, next) { next() },
|
|
90
|
-
preHandler: function (request, reply, next) { next() }
|
|
91
|
-
},
|
|
92
|
-
staticCSP: true,
|
|
93
|
-
transformStaticCSP: (header) => header,
|
|
94
|
-
transformSpecification: (swaggerObject, request, reply) => { return swaggerObject },
|
|
95
|
-
transformSpecificationClone: true
|
|
96
|
-
})
|
|
50
|
+
const User = mongoose.model('Users', userSchema)
|
|
97
51
|
|
|
98
|
-
|
|
52
|
+
await mongoose.connect(process.env.MONGODB_URL)
|
|
99
53
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
process.exit(1)
|
|
104
|
-
}
|
|
105
|
-
})
|
|
54
|
+
const app = Fastify({ logger: true })
|
|
55
|
+
app.register(Crudify, { url: '/users', Model: User, scope: false }) // see "Scope and authorize"
|
|
56
|
+
await app.listen({ port: 3000 })
|
|
106
57
|
```
|
|
107
58
|
|
|
108
|
-
|
|
59
|
+
| Route | Does | Built in |
|
|
60
|
+
|---|---|---|
|
|
61
|
+
| `GET /users` | paginated list | sanitized `filters` / `options`, limit cap |
|
|
62
|
+
| `GET /users/:id` | one document | 404 when missing or out of scope |
|
|
63
|
+
| `POST /users` | create one document, or an array (bulk) | schema validation, save hooks run |
|
|
64
|
+
| `PUT /users/:id` | update fields | only your writable fields, validators run |
|
|
65
|
+
| `DELETE /users/:id` | delete | 404 when missing or out of scope |
|
|
109
66
|
|
|
110
|
-
|
|
67
|
+
The URLs and response shapes are the same as in 1.x. A runnable example with authentication, two tenants and a custom action lives in [`example/`](example/).
|
|
111
68
|
|
|
112
|
-
|
|
69
|
+
## Secure by default
|
|
113
70
|
|
|
114
|
-
|
|
71
|
+
Without any configuration:
|
|
115
72
|
|
|
116
|
-
|
|
117
|
-
|
|
73
|
+
- `filters` accept a short allowlist of operators with bounded depth and size. `$where`, `$expr`, `$function`, `$regex`, `$text` and friends are refused.
|
|
74
|
+
- `"/text/"` searches are **escaped literals**, never a client-supplied regex, so they cannot be used for ReDoS.
|
|
75
|
+
- `options` only honour `page`, `limit` and `sort`. `limit` defaults to 50 and is capped at 100; `populate`, `select`, `lean` and `pagination: false` from the client are ignored.
|
|
76
|
+
- Writes drop `_id`, `__v` and the timestamps, accept no update operators besides `$set` / `$unset`, and refuse operators nested inside values.
|
|
77
|
+
- Fields with `select: false` in your schema cannot be filtered or sorted on (it would be a search oracle).
|
|
78
|
+
- Bulk creation goes through `Model.create`, so `pre('save')` / `post('save')` hooks always run, and an invalid item inserts nothing.
|
|
79
|
+
- Errors are mapped to a fixed shape. Duplicate keys become a generic `409`; unexpected errors become `500 Internal error` (the detail goes to your logs, never to the client).
|
|
80
|
+
- Invalid ids answer `404` without touching the database.
|
|
118
81
|
|
|
119
|
-
|
|
120
|
-
import paginate from 'mongoose-paginate-v2'; // Required for pagination
|
|
121
|
-
import extendMongoose from 'mongoose-schema-jsonschema'; // Required for body and response schema auto generation
|
|
82
|
+
What it does **not** do on its own is decide *who* may see *which* documents. That is what `authorize` and `scope` are for.
|
|
122
83
|
|
|
123
|
-
|
|
84
|
+
## Authentication and authorization
|
|
124
85
|
|
|
125
|
-
|
|
86
|
+
Crudify does **not** authenticate users and does not include any permission system. It stays out of that on purpose and gives you two seams so any tool can plug in: [`@fastify/auth`](https://github.com/fastify/fastify-auth), JWT plugins, sessions, Casbin, your own checks.
|
|
126
87
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
age: {
|
|
133
|
-
type: Number,
|
|
134
|
-
required: true,
|
|
135
|
-
},
|
|
136
|
-
email: {
|
|
137
|
-
type: String,
|
|
138
|
-
required: true,
|
|
139
|
-
},
|
|
140
|
-
}, {
|
|
141
|
-
timestamps: true,
|
|
142
|
-
});
|
|
88
|
+
1. Authenticate with a Fastify hook or `routeOptions.preHandler` (this is where `req.user` gets set).
|
|
89
|
+
2. `authorize(req, action)` answers *may this user do this action?* and throws (or returns `false`) to deny.
|
|
90
|
+
3. `scope(req, action)` answers *which documents is this user limited to?* and returns a Mongo filter.
|
|
91
|
+
|
|
92
|
+
[`example/app.js`](example/app.js) is a complete, tested setup with `@fastify/auth`, two accounts and roles. A Casbin recipe is under [Recipes](#recipes).
|
|
143
93
|
|
|
144
|
-
|
|
94
|
+
## Query language
|
|
145
95
|
|
|
146
|
-
|
|
147
|
-
const UserModel = mongoose.model('Users', userSchema);
|
|
96
|
+
Query params are JSON strings:
|
|
148
97
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
UserSchema
|
|
152
|
-
}
|
|
98
|
+
```
|
|
99
|
+
GET /users?filters={"age":{"$gte":18},"name":"/ana/"}&options={"page":2,"limit":20,"sort":"-createdAt name"}
|
|
153
100
|
```
|
|
154
101
|
|
|
155
|
-
|
|
102
|
+
| Piece | Allowed |
|
|
103
|
+
|---|---|
|
|
104
|
+
| Comparison | `$eq $ne $gt $gte $lt $lte` with plain values |
|
|
105
|
+
| Lists | `$in $nin` (and `$all`, opt-in) with arrays of plain values |
|
|
106
|
+
| Other | `$exists` (boolean); `$size` (opt-in) |
|
|
107
|
+
| Logical | `$or $and` (and `$nor`, opt-in), non-empty arrays |
|
|
108
|
+
| Text | `"/text/"` as a value: case-insensitive *contains* on an escaped literal (`query.search: 'prefix'` makes it `^text`, which can use an index) |
|
|
109
|
+
| Sort | a string (`"-createdAt name"`) or an object (`{"name": 1}`), field names validated |
|
|
110
|
+
| Never | `$where $expr $function $accumulator $regex $text $jsonSchema $elemMatch` |
|
|
111
|
+
|
|
112
|
+
The default limits (all configurable through `query`) are depth 4, 100 keys, 1000 array items, 20 branches per `$or`/`$and`, 64 characters of search text and 5 sort fields. Anything else is a `400` with `code: "invalid_query"`.
|
|
113
|
+
|
|
114
|
+
## Options
|
|
115
|
+
|
|
116
|
+
`fastify.register(Crudify, options)`:
|
|
117
|
+
|
|
118
|
+
| Option | Default | Meaning |
|
|
119
|
+
|---|---|---|
|
|
120
|
+
| `url` | required | Base path, e.g. `/users`. May contain params: `/orders/:orderId/lines` |
|
|
121
|
+
| `Model` | required | Mongoose model (with `paginate` if `list` is enabled) |
|
|
122
|
+
| `methods` | all five | Subset of `list get create update delete` |
|
|
123
|
+
| `scope` | none (warns) | `(req, action) => filter`, or `false` for "no restriction" |
|
|
124
|
+
| `authorize` | none | `(req, action) => void`; throw or return `false` to deny |
|
|
125
|
+
| `hooks` | `{}` | `beforeCreate afterCreate beforeUpdate afterUpdate beforeDelete afterDelete afterList` |
|
|
126
|
+
| `serialize` | none | `(doc, req) => object`, applied to every document sent |
|
|
127
|
+
| `mapError` | built in | `(err, req) => ({ status, body }) \| undefined`; `false` to use the app's own error handler |
|
|
128
|
+
| `query` | see below | Sanitizer settings for `filters` / `options` |
|
|
129
|
+
| `fields` | none | `writable` (allowlist), `readonly` (denylist), `hidden` (not filterable) |
|
|
130
|
+
| `bulk` | `{ max: 100, insertMany: false }` | Bulk create limits; `false` disables arrays |
|
|
131
|
+
| `lean` | `false` | Return plain objects (faster; skips getters, virtuals and `toJSON` transforms) |
|
|
132
|
+
| `select` | none | Fixed projection for reads and updates |
|
|
133
|
+
| `sanitizer` | `true` | `false` disables it (1.x behaviour, logs a warning) or pass `{ filter, options, update, create }` to replace pieces |
|
|
134
|
+
| `JSONSchema` | none | JSON Schema of the model: validates bodies and serializes responses |
|
|
135
|
+
| `schema` | none | Fastify schema per verb: `{ list, get, create, update, delete }` |
|
|
136
|
+
| `routeOptions` | `{}` | Fastify route options for every route (`preHandler`, `config`, `bodyLimit`...) |
|
|
137
|
+
| `handlers` | none | Replace one built-in verb: `{ create: (req, reply, ctx) => ... }` |
|
|
138
|
+
| `routes` | none | `(api, ctx) => void`: add your own routes |
|
|
139
|
+
| `actions` | none | Non-CRUD operations on one document, see below |
|
|
140
|
+
| `strict` | `false` | Throw at startup if `scope` is missing or the sanitizer is disabled |
|
|
141
|
+
|
|
142
|
+
`query`: `operators`, `maxDepth`, `maxKeys`, `maxArray`, `maxBranches`, `search` (`'contains' | 'prefix' | false`), `maxSearchLength`, `filterable` (allowlist of root fields), `defaultLimit` (50), `maxLimit` (100), `maxSort`, `populate` (paths a client may populate).
|
|
143
|
+
|
|
144
|
+
`createdAt`, `updatedAt` (including custom names from `timestamps`), `_id`, `__v` and the root keys of your scope are always read-only for clients. Registering the plugin with invalid options throws immediately.
|
|
145
|
+
|
|
146
|
+
## Errors
|
|
147
|
+
|
|
148
|
+
Every error uses one body, the same `{ status, error, message }` shape the 404 always had, plus an optional `code`:
|
|
149
|
+
|
|
150
|
+
| Case | Status | Notes |
|
|
151
|
+
|---|---|---|
|
|
152
|
+
| Not found, out of scope, invalid id | 404 | `ID: <id> not found` |
|
|
153
|
+
| Invalid query, body or operators | 400 | `code: "invalid_query"` / `"invalid_body"` |
|
|
154
|
+
| Mongoose validation | 400 | `Fields: [a, b] are required and cannot be empty`, or `Invalid fields: [...]` with `details.fields`; custom messages stay private |
|
|
155
|
+
| Cast error | 400 | `Invalid value for "<path>"` |
|
|
156
|
+
| `authorize` / `scope` deny | 403 | `Forbidden` (or your `CrudifyError`) |
|
|
157
|
+
| Bulk over `bulk.max` | 413 | |
|
|
158
|
+
| Duplicate key (E11000) | 409 | `code: "duplicate_key"`; **never** the collection, index or value |
|
|
159
|
+
| Version conflict | 409 | `code: "version_conflict"` |
|
|
160
|
+
| Anything else | 500 | `Internal error`; the real error is logged |
|
|
161
|
+
|
|
162
|
+
To show a message to the client from your own code, throw a `CrudifyError`:
|
|
156
163
|
|
|
157
164
|
```js
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
import { UserModel, UserSchema } from './models/user.js';
|
|
161
|
-
|
|
162
|
-
const routes = ( fastify, opts, done ) => {
|
|
163
|
-
fastify.register(Crudify, {
|
|
164
|
-
url: '/users',
|
|
165
|
-
Model: UserModel
|
|
166
|
-
JSONSchema: UserSchema
|
|
167
|
-
})
|
|
168
|
-
}
|
|
165
|
+
import { CrudifyError } from '@aaroncadillac/crudify-mongo'
|
|
166
|
+
throw new CrudifyError(409, 'This order is already paid', { code: 'order_paid' })
|
|
169
167
|
```
|
|
170
168
|
|
|
171
|
-
|
|
169
|
+
`toErrorResponse(err)` is exported if you want the same mapping in your own `setErrorHandler`.
|
|
172
170
|
|
|
173
|
-
|
|
171
|
+
## Scope and authorize
|
|
174
172
|
|
|
175
|
-
|
|
176
|
-
|
|
173
|
+
`scope` is a filter ANDed with every read and write, so a document outside it is simply "not found":
|
|
174
|
+
|
|
175
|
+
```js
|
|
176
|
+
app.register(Crudify, {
|
|
177
|
+
url: '/orders',
|
|
178
|
+
Model: Order,
|
|
179
|
+
scope: (req) => ({ accountId: req.user.accountId })
|
|
180
|
+
})
|
|
177
181
|
```
|
|
178
182
|
|
|
179
|
-
|
|
183
|
+
- **list / get / update / delete:** the scope is combined with the client filter and the id. If a key collides (the client also filters on `accountId`), both conditions are kept with `$and`, so the client can never override the scope.
|
|
184
|
+
- **create:** root keys with an equality value are *forced* into the new document (the client value is ignored). With `{ $in: [...] }` the client must send a value from the list (`400` if missing, `403` if not allowed).
|
|
185
|
+
- **update:** root keys of the scope can't be rewritten, so a document can never be moved out of its scope. If your scope uses `$or`, list the involved fields in `fields.readonly`.
|
|
186
|
+
- `scope` must return a plain object. Anything else is a `403` (fail closed). Return `{}` to say "no restriction" explicitly, or pass `scope: false`.
|
|
187
|
+
- `authorize` runs first, before any query. Use it for role checks that don't depend on the document; use `scope` for anything about *which* documents (it is atomic: no read-then-check race).
|
|
180
188
|
|
|
181
|
-
|
|
189
|
+
## Hooks and request order
|
|
182
190
|
|
|
183
191
|
```js
|
|
184
|
-
|
|
192
|
+
app.register(Crudify, {
|
|
193
|
+
url: '/orders',
|
|
194
|
+
Model: Order,
|
|
195
|
+
hooks: {
|
|
196
|
+
beforeCreate: async (data, req) => ({ ...data, createdBy: req.user.id }), // return the (new) data
|
|
197
|
+
afterCreate: async (docOrDocs, req) => {},
|
|
198
|
+
beforeUpdate: async (changes, req) => changes,
|
|
199
|
+
afterUpdate: async (doc, req) => {},
|
|
200
|
+
beforeDelete: async (doc, req) => { if (doc.paid) throw new CrudifyError(409, 'Paid orders cannot be deleted') },
|
|
201
|
+
afterDelete: async (doc, req) => {},
|
|
202
|
+
afterList: async (result, req) => result // the paginate result; return it or a new one
|
|
203
|
+
}
|
|
204
|
+
})
|
|
205
|
+
```
|
|
185
206
|
|
|
186
|
-
|
|
187
|
-
import paginate from 'mongoose-paginate-v2'; // Required for pagination
|
|
207
|
+
Order for every request: Fastify hooks and schema validation, `routeOptions.preHandler`, cheap structural checks (id format, body shape, bulk size), `authorize`, `scope`, sanitizing, `before*`, the Mongo operation, `after*`, `serialize`. Any hook can stop the request by throwing a `CrudifyError`. Declaring `beforeDelete` costs one extra query (it needs the document); without it, delete is a single `findOneAndDelete`. An error thrown from an `after*` hook happens after the write: use `onResponse` for non-critical side effects.
|
|
188
208
|
|
|
189
|
-
|
|
209
|
+
`req.crudify` is `{ action, filter, doc }` for the current request, readable from your own Fastify hooks.
|
|
190
210
|
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
211
|
+
## Custom routes, actions and overrides
|
|
212
|
+
|
|
213
|
+
Everything below shares the same `authorize`, `scope` and error handling as the built-in verbs, and receives a context `ctx`:
|
|
214
|
+
|
|
215
|
+
```js
|
|
216
|
+
app.register(Crudify, {
|
|
217
|
+
url: '/orders',
|
|
218
|
+
Model: Order,
|
|
219
|
+
scope: (req) => ({ accountId: req.user.accountId }),
|
|
220
|
+
authorize: (req, action) => { if (action === 'close' && req.user.role !== 'admin') throw new CrudifyError(403, 'Admins only') },
|
|
221
|
+
|
|
222
|
+
// 1. an action on one document: POST /orders/:id/close (the document arrives loaded, in scope)
|
|
223
|
+
actions: {
|
|
224
|
+
close: {
|
|
225
|
+
handler: async (req, reply, ctx) => {
|
|
226
|
+
const order = req.crudify.doc
|
|
227
|
+
order.status = 'closed'
|
|
228
|
+
await order.save()
|
|
229
|
+
return ctx.serialize(order, req)
|
|
230
|
+
}
|
|
231
|
+
}
|
|
199
232
|
},
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
233
|
+
|
|
234
|
+
// 2. free-form routes
|
|
235
|
+
routes: (api) => {
|
|
236
|
+
api.get('/stats', { action: 'list' }, async (req, reply, ctx) => ({
|
|
237
|
+
open: await ctx.Model.countDocuments(await ctx.where(req, 'list', { status: 'open' }))
|
|
238
|
+
}))
|
|
239
|
+
api.get('/:id/light', { load: true }, async (req) => ({ id: req.crudify.doc._id }))
|
|
203
240
|
},
|
|
204
|
-
}, {
|
|
205
|
-
timestamps: true,
|
|
206
|
-
});
|
|
207
241
|
|
|
208
|
-
|
|
242
|
+
// 3. replace one built-in verb, keeping authorize + scope
|
|
243
|
+
handlers: {
|
|
244
|
+
list: async (req, reply, ctx) => ({ total: (await ctx.list(req)).totalDocs })
|
|
245
|
+
}
|
|
246
|
+
})
|
|
247
|
+
```
|
|
209
248
|
|
|
210
|
-
|
|
249
|
+
`actions.<name>` options: `handler`, `method` (`POST`), `path` (`/:id/<name>`), `load` (`true`), `action` (the name given to `authorize`/`scope`, default the key), plus any Fastify route option such as `schema`.
|
|
211
250
|
|
|
212
|
-
|
|
213
|
-
UserModel
|
|
214
|
-
}
|
|
215
|
-
```
|
|
251
|
+
`api.get|post|put|patch|delete(path, [options], handler)`; options are Fastify route options plus `action` (what `authorize`/`scope` see; defaults to `get` for GET, `delete` for DELETE, `update` otherwise) and `load` (load the document into `req.crudify.doc`).
|
|
216
252
|
|
|
217
|
-
|
|
253
|
+
`ctx` has `Model`, `url`, `scope(req, action)`, `where(req, action, base)` (a filter with the scope applied), `load(req, action, id)` (a real Mongoose document, or 404), `list(req)` (sanitized + scoped paginate), `sanitize.{filter, options, update, create, query}`, `serialize`, `notFound` and `checkId`.
|
|
254
|
+
|
|
255
|
+
> `additionalRoutes` (a function, or an array of `{ method, url, handler }`) still works but is deprecated and will be removed in 3.0. Use `routes` or `actions`.
|
|
256
|
+
|
|
257
|
+
## Recipes
|
|
258
|
+
|
|
259
|
+
**A tenant resource in five lines.** Multi-tenancy is your domain, so keep the factory in your app:
|
|
218
260
|
|
|
219
261
|
```js
|
|
220
|
-
|
|
262
|
+
const owned = (url, Model, extra = {}) => ({ url, Model, scope: (req) => ({ accountId: req.user.accountId }), ...extra })
|
|
263
|
+
app.register(Crudify, owned('/tables', Table))
|
|
264
|
+
app.register(Crudify, owned('/menus', Menu, { methods: ['list', 'get'] }))
|
|
265
|
+
```
|
|
221
266
|
|
|
222
|
-
|
|
267
|
+
**Sub-resources.** The parent id is just part of the URL and the scope:
|
|
223
268
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
269
|
+
```js
|
|
270
|
+
app.register(Crudify, {
|
|
271
|
+
url: '/orders/:orderId/lines',
|
|
272
|
+
Model: Line,
|
|
273
|
+
scope: async (req) => {
|
|
274
|
+
if (!(await Order.exists({ _id: req.params.orderId, accountId: req.user.accountId }))) throw new CrudifyError(404, 'Not found')
|
|
275
|
+
return { orderId: req.params.orderId } // forced on create, ANDed on the rest
|
|
231
276
|
}
|
|
232
|
-
}
|
|
277
|
+
})
|
|
278
|
+
```
|
|
233
279
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
280
|
+
**Casbin** (or any policy engine), with no extra dependency in Crudify:
|
|
281
|
+
|
|
282
|
+
```js
|
|
283
|
+
const ACTION = { list: 'read', get: 'read', create: 'create', update: 'update', delete: 'delete' }
|
|
284
|
+
|
|
285
|
+
app.register(Crudify, {
|
|
286
|
+
url: '/orders',
|
|
287
|
+
Model: Order,
|
|
288
|
+
authorize: async (req, action) => {
|
|
289
|
+
const allowed = await enforcer.enforce(req.user.id, req.user.accountId, 'orders', ACTION[action] ?? action)
|
|
290
|
+
if (!allowed) throw new CrudifyError(403, 'Forbidden')
|
|
291
|
+
},
|
|
292
|
+
scope: (req) => ({ accountId: req.user.accountId }) // the policy domain doubles as the data scope
|
|
293
|
+
})
|
|
237
294
|
```
|
|
238
295
|
|
|
239
|
-
|
|
296
|
+
**Hide fields from responses:**
|
|
240
297
|
|
|
241
298
|
```js
|
|
242
|
-
|
|
299
|
+
serialize: (doc) => { const { passwordHash, ...rest } = doc.toObject({ flattenObjectIds: true }); return rest }
|
|
300
|
+
```
|
|
243
301
|
|
|
244
|
-
|
|
245
|
-
import Crudify from 'crudify-mongo';
|
|
246
|
-
import { dbConnection } from './db-connection';
|
|
247
|
-
import { UserModel } from './models/user';
|
|
302
|
+
## The sanitizer on its own
|
|
248
303
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
304
|
+
The sanitizer is a separate module you can use in your own handlers:
|
|
305
|
+
|
|
306
|
+
```js
|
|
307
|
+
import { sanitizeFilter, sanitizeOptions, sanitizeUpdate, createSanitizer, parseJson } from '@aaroncadillac/crudify-mongo/sanitizer'
|
|
252
308
|
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
Model: UserModel
|
|
257
|
-
})
|
|
258
|
-
}
|
|
309
|
+
const filter = sanitizeFilter(parseJson(req.query.filters, 'filters'), { maxDepth: 2 })
|
|
310
|
+
const { filter: f, options, update, create } = createSanitizer({ maxLimit: 25, writable: ['name'] }) // compile once, reuse
|
|
311
|
+
```
|
|
259
312
|
|
|
260
|
-
|
|
261
|
-
fastify.register(routes)
|
|
313
|
+
Pass `sanitizer: { filter: myFn }` to Crudify to replace a piece, or `sanitizer: false` to turn it off (not recommended).
|
|
262
314
|
|
|
315
|
+
## JSON Schema and Swagger
|
|
263
316
|
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
}
|
|
269
|
-
})
|
|
317
|
+
Give Crudify the JSON Schema of your model (for example from [`mongoose-schema-jsonschema`](https://github.com/DScheglov/mongoose-schema-jsonschema)) and it validates bodies and serializes responses with it:
|
|
318
|
+
|
|
319
|
+
```js
|
|
320
|
+
app.register(Crudify, { url: '/users', Model: User, JSONSchema: userJsonSchema, scope: false })
|
|
270
321
|
```
|
|
271
322
|
|
|
272
|
-
|
|
323
|
+
The list response is typed as the paginate result, `POST` accepts one object or an array, read-only fields are removed from the body schema (so a key forced by your scope is never "required" from the client), and `x-ref` keys are stripped. Responses drop `required`, so `select` and `serialize` can hide fields freely. Use `schema: { list: {...}, ... }` to override any verb, and `@fastify/swagger` picks everything up.
|
|
324
|
+
|
|
325
|
+
## Performance
|
|
273
326
|
|
|
274
|
-
|
|
327
|
+
Everything that can be computed is computed once at registration: allowlist `Set`s, the sanitizer, route schemas, error handler and the context. Per request there is a single `JSON.parse` for each query param, one pass of the sanitizer that builds its output directly, one query (paginate does two) and no `try/catch` per route. `node bench/run.js` (no extra dependencies) measures it; on an Apple-silicon laptop with a stubbed model, a typical filter sanitizes in about 0.8 µs and Crudify adds roughly 0.5-0.8 µs per request over a bare Fastify route. `lean: true` skips Mongoose document hydration on reads when you don't need getters, virtuals or `toJSON` transforms.
|
|
275
328
|
|
|
276
|
-
|
|
329
|
+
## Acknowledgements
|
|
330
|
+
|
|
331
|
+
Inspired by [fastify-mongoose-crud](https://github.com/paranoiasystem/fastify-autocrud).
|
|
277
332
|
|
|
278
333
|
## License
|
|
279
334
|
|
|
280
335
|
[Mozilla Public License 2.0](/LICENSE)
|
|
281
|
-
|