fastify 2.10.0 → 2.11.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 +7 -0
- package/build/build-validation.js +8 -0
- package/docs/Ecosystem.md +5 -1
- package/docs/Hooks.md +32 -14
- package/docs/Plugins.md +1 -0
- package/docs/Routes.md +95 -6
- package/docs/Server.md +50 -1
- package/docs/TypeScript.md +30 -7
- package/docs/Validation-and-Serialization.md +74 -1
- package/fastify.d.ts +25 -1
- package/fastify.js +38 -2
- package/lib/configValidator.js +99 -52
- package/lib/contentTypeParser.js +4 -4
- package/lib/context.js +2 -1
- package/lib/logger.js +2 -2
- package/lib/route.js +18 -3
- package/lib/schemas.js +1 -1
- package/lib/symbols.js +1 -0
- package/lib/validation.js +10 -5
- package/package.json +20 -19
- package/test/404s.test.js +40 -0
- package/test/decorator.test.js +48 -0
- package/test/fastify-instance.test.js +29 -0
- package/test/hooks.test.js +23 -7
- package/test/input-validation.test.js +126 -0
- package/test/internals/initialConfig.test.js +2 -0
- package/test/logger.test.js +309 -0
- package/test/proto-poisoning.test.js +76 -0
- package/test/route-hooks.test.js +23 -14
- package/test/schemas.test.js +126 -0
- package/test/types/index.ts +31 -1
package/README.md
CHANGED
|
@@ -152,6 +152,7 @@ matters to you.
|
|
|
152
152
|
* <a href="https://github.com/fastify/fastify/blob/master/docs/Hooks.md"><code><b>Hooks</b></code></a>
|
|
153
153
|
* <a href="https://github.com/fastify/fastify/blob/master/docs/Decorators.md"><code><b>Decorators</b></code></a>
|
|
154
154
|
* <a href="https://github.com/fastify/fastify/blob/master/docs/Validation-and-Serialization.md"><code><b>Validation and Serialization</b></code></a>
|
|
155
|
+
* <a href="https://github.com/fastify/fastify/blob/master/docs/Fluent-Schema.md"><code><b>Fluent Schema</b></code></a>
|
|
155
156
|
* <a href="https://github.com/fastify/fastify/blob/master/docs/Lifecycle.md"><code><b>Lifecycle</b></code></a>
|
|
156
157
|
* <a href="https://github.com/fastify/fastify/blob/master/docs/Reply.md"><code><b>Reply</b></code></a>
|
|
157
158
|
* <a href="https://github.com/fastify/fastify/blob/master/docs/Request.md"><code><b>Request</b></code></a>
|
|
@@ -215,6 +216,12 @@ Great contributors on a specific area in the Fastify ecosystem will be invited t
|
|
|
215
216
|
* [__Trivikram Kamat__](https://github.com/trivikr), <https://twitter.com/trivikram>, <https://www.npmjs.com/~trivikr>
|
|
216
217
|
* [__Nathan Woltman__](https://github.com/nwoltman), <https://twitter.com/NathanWoltman>, <https://www.npmjs.com/~nwoltman>
|
|
217
218
|
|
|
219
|
+
## Hosted by
|
|
220
|
+
|
|
221
|
+
[<img src="https://github.com/openjs-foundation/cross-project-council/blob/master/logos/openjsf-color.png?raw=true" width="250px;"/>](https://openjsf.org/projects/#incubating)
|
|
222
|
+
|
|
223
|
+
We are currently an [incubated project](https://openjsf.org/blog/2019/11/20/web-framework-fastify-joins-openjs-foundation-as-an-incubating-project/) at the OpenJS Foundation.
|
|
224
|
+
|
|
218
225
|
## Acknowledgements
|
|
219
226
|
|
|
220
227
|
This project is kindly sponsored by:
|
|
@@ -15,9 +15,12 @@ const ajv = new Ajv({
|
|
|
15
15
|
const defaultInitOptions = {
|
|
16
16
|
bodyLimit: 1024 * 1024, // 1 MiB
|
|
17
17
|
caseSensitive: true,
|
|
18
|
+
disableRequestLogging: false,
|
|
18
19
|
ignoreTrailingSlash: false,
|
|
19
20
|
maxParamLength: 100,
|
|
20
21
|
onProtoPoisoning: 'error',
|
|
22
|
+
// TODO v3: default should be 'error'
|
|
23
|
+
onConstructorPoisoning: 'ignore',
|
|
21
24
|
pluginTimeout: 10000,
|
|
22
25
|
requestIdHeader: 'request-id',
|
|
23
26
|
requestIdLogLabel: 'reqId'
|
|
@@ -62,8 +65,13 @@ const schema = {
|
|
|
62
65
|
then: { setDefaultValue: true }
|
|
63
66
|
},
|
|
64
67
|
ignoreTrailingSlash: { type: 'boolean', default: defaultInitOptions.ignoreTrailingSlash },
|
|
68
|
+
disableRequestLogging: {
|
|
69
|
+
type: 'boolean',
|
|
70
|
+
default: false
|
|
71
|
+
},
|
|
65
72
|
maxParamLength: { type: 'integer', default: defaultInitOptions.maxParamLength },
|
|
66
73
|
onProtoPoisoning: { type: 'string', default: defaultInitOptions.onProtoPoisoning },
|
|
74
|
+
onConstructorPoisoning: { type: 'string', default: defaultInitOptions.onConstructorPoisoning },
|
|
67
75
|
pluginTimeout: { type: 'integer', default: defaultInitOptions.pluginTimeout },
|
|
68
76
|
requestIdHeader: { type: 'string', default: defaultInitOptions.requestIdHeader },
|
|
69
77
|
requestIdLogLabel: { type: 'string', default: defaultInitOptions.requestIdLogLabel }
|
package/docs/Ecosystem.md
CHANGED
|
@@ -51,6 +51,7 @@ Plugins maintained by the fastify team are listed under [Core](#core) while plug
|
|
|
51
51
|
- [`fastify-405`](https://github.com/Eomm/fastify-405) Fastify plugin that adds 405 HTTP status to your routes
|
|
52
52
|
- [`fastify-amqp`](https://github.com/RafaelGSS/fastify-amqp) Fastify AMQP connection plugin, to use with RabbitMQ or another connector. Just a wrapper to [`amqplib`](https://github.com/squaremo/amqp.node).
|
|
53
53
|
- [`fastify-angular-universal`](https://github.com/exequiel09/fastify-angular-universal) Angular server-side rendering support using [`@angular/platform-server`](https://github.com/angular/angular/tree/master/packages/platform-server) for Fastify
|
|
54
|
+
- [`fastify-auth0-verify`](https://github.com/nearform/fastify-auth0-verify): Auth0 verification plugin for Fastify, internally uses [fastify-jwt](https://npm.im/fastify-jwt) and [jsonwebtoken](https://npm.im/jsonwebtoken).
|
|
54
55
|
- [`fastify-autocrud`](https://github.com/paranoiasystem/fastify-autocrud) Plugin for autogenerate CRUD routes as fast as possible.
|
|
55
56
|
- [`fastify-babel`](https://github.com/cfware/fastify-babel) Fastify plugin for development servers which require babel transformations of JavaScript sources.
|
|
56
57
|
- [`fastify-blipp`](https://github.com/PavelPolyakov/fastify-blipp) Prints your routes to the console, so you definitely know which endpoints are available.
|
|
@@ -64,6 +65,7 @@ Plugins maintained by the fastify team are listed under [Core](#core) while plug
|
|
|
64
65
|
- [`fastify-decorators`](https://github.com/L2jLiga/fastify-decorators) Fastify plugin that provides the set of TypeScript decorators.
|
|
65
66
|
- [`fastify-dynamodb`](https://github.com/matrus2/fastify-dynamodb) AWS DynamoDB plugin for Fastify. It exposes [AWS.DynamoDB.DocumentClient()](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html) object.
|
|
66
67
|
- [`fastify-error-page`](https://github.com/hemerajs/fastify-error-page) Fastify plugin to print errors in structured HTML to the browser.
|
|
68
|
+
- [`fastify-errors-properties`](https://github.com/ShogunPanda/fastify-errors-properties) A error handling plugin for Fastify that enables additional properties in errors.
|
|
67
69
|
- [`fastify-favicon`](https://github.com/smartiniOnGitHub/fastify-favicon) Fastify plugin to serve default favicon.
|
|
68
70
|
- [`fastify-feature-flags`](https://gitlab.com/m03geek/fastify-feature-flags) Fastify feature flags plugin with multiple providers support (e.g. env, [config](http://lorenwest.github.io/node-config/), [unleash](https://unleash.github.io/)).
|
|
69
71
|
- [`fastify-file-upload`](https://github.com/huangang/fastify-file-upload) Fastify plugin for uploading files.
|
|
@@ -75,6 +77,7 @@ Plugins maintained by the fastify team are listed under [Core](#core) while plug
|
|
|
75
77
|
- [`fastify-healthcheck`](https://github.com/smartiniOnGitHub/fastify-healthcheck) Fastify plugin to serve an health check route and a probe script.
|
|
76
78
|
- [`fastify-hemera`](https://github.com/hemerajs/fastify-hemera) Fastify Hemera plugin, for writing reliable & fault-tolerant microservices with [nats.io](https://nats.io/).
|
|
77
79
|
- [`fastify-http2https`](https://github.com/lolo32/fastify-http2https) Redirect HTTP requests to HTTPS, both using the same port number, or different response on HTTP and HTTPS.
|
|
80
|
+
- [`fastify-https-redirect`](https://github.com/tomsvogel/fastify-https-redirect) Fastify plugin for auto redirect from http to https
|
|
78
81
|
- [`fastify-http-client`](https://github.com/kenuyx/fastify-http-client) Plugin to send HTTP(s) requests. Built upon [urllib](https://github.com/node-modules/urllib).
|
|
79
82
|
- [`fastify-influxdb`](https://github.com/alex-ppg/fastify-influxdb) Fastify InfluxDB plugin connecting to an InfluxDB instance via the Influx default package.
|
|
80
83
|
- [`fastify-jwt-authz`](https://github.com/Ethan-Arrowood/fastify-jwt-authz) JWT user scope verifier.
|
|
@@ -90,7 +93,7 @@ Plugins maintained by the fastify team are listed under [Core](#core) while plug
|
|
|
90
93
|
- [`fastify-mongo-memory`](https://github.com/chapuletta/fastify-mongo-memory) Fastify MongoDB in Memory Plugin for testing support.
|
|
91
94
|
- [`fastify-mongoose-api`](https://github.com/jeka-kiselyov/fastify-mongoose-api) Fastify plugin to create REST API methods based on Mongoose MongoDB models.
|
|
92
95
|
- [`fastify-mongoose-driver`](https://github.com/alex-ppg/fastify-mongoose) Fastify Mongoose plugin that connects to a MongoDB via the Mongoose plugin with support for Models.
|
|
93
|
-
- [`fastify-multer`](https://github.com/fox1t/multer) Multer is a plugin for handling multipart/form-data, which is primarily used for uploading files.
|
|
96
|
+
- [`fastify-multer`](https://github.com/fox1t/fastify-multer) Multer is a plugin for handling multipart/form-data, which is primarily used for uploading files.
|
|
94
97
|
- [`fastify-nats`](https://github.com/mahmed8003/fastify-nats) Plugin to share [NATS](http://nats.io) client across Fastify.
|
|
95
98
|
- [`fastify-no-additional-properties`](https://github.com/greguz/fastify-no-additional-properties) Add `additionalProperties: false` by default to your JSON Schemas.
|
|
96
99
|
- [`fastify-no-icon`](https://github.com/jsumners/fastify-no-icon) Plugin to eliminate thrown errors for `/favicon.ico` requests.
|
|
@@ -100,6 +103,7 @@ Plugins maintained by the fastify team are listed under [Core](#core) while plug
|
|
|
100
103
|
- [`fastify-openapi-glue`](https://github.com/seriousme/fastify-openapi-glue) Glue for Open Api specifications in Fastify, autogenerates routes based on an Open Api Specification
|
|
101
104
|
- [`fastify-oracle`](https://github.com/cemremengu/fastify-oracle) Attaches an [`oracledb`](https://github.com/oracle/node-oracledb) connection pool to a Fastify server instance.
|
|
102
105
|
- [`fastify-orientdb`](https://github.com/mahmed8003/fastify-orientdb) Fastify OrientDB connection plugin, with which you can share the OrientDB connection across every part of your server.
|
|
106
|
+
- [`fastify-qs`](https://github.com/webdevium/fastify-qs) A plugin for Fastify that adds support for parsing URL query parameters with [qs](https://github.com/ljharb/qs).
|
|
103
107
|
- [`fastify-rbac`](https://gitlab.com/m03geek/fastify-rbac) Fastify role-based access control plugin.
|
|
104
108
|
- [`fastify-register-routes`](https://github.com/israeleriston/fastify-register-routes) Plugin to automatically load routes from a specified path and optionally limit loaded file names by a regular expression.
|
|
105
109
|
- [`fastify-response-time`](https://github.com/lolo32/fastify-response-time) Add `X-Response-Time` header at each request for Fastify, in milliseconds.
|
package/docs/Hooks.md
CHANGED
|
@@ -7,14 +7,14 @@ Hooks are registered with the `fastify.addHook` method and allow you to listen t
|
|
|
7
7
|
By using hooks you can interact directly with the lifecycle of Fastify. There are Request/Reply hooks and application hooks:
|
|
8
8
|
|
|
9
9
|
- [Request/Reply Hooks](#requestreply-hooks)
|
|
10
|
-
- [onRequest](#
|
|
11
|
-
- [preParsing](#
|
|
12
|
-
- [preValidation](#
|
|
13
|
-
- [preHandler](#
|
|
14
|
-
- [preSerialization](#
|
|
15
|
-
- [onError](#
|
|
16
|
-
- [onSend](#
|
|
17
|
-
- [onResponse](#
|
|
10
|
+
- [onRequest](#onrequest)
|
|
11
|
+
- [preParsing](#preparsing)
|
|
12
|
+
- [preValidation](#prevalidation)
|
|
13
|
+
- [preHandler](#prehandler)
|
|
14
|
+
- [preSerialization](#preserialization)
|
|
15
|
+
- [onError](#onerror)
|
|
16
|
+
- [onSend](#onsend)
|
|
17
|
+
- [onResponse](#onresponse)
|
|
18
18
|
- [Application Hooks](#application-hooks)
|
|
19
19
|
- [onClose](#onclose)
|
|
20
20
|
- [onRoute](#onroute)
|
|
@@ -280,9 +280,24 @@ fastify.addHook('onRoute', (routeOptions) => {
|
|
|
280
280
|
routeOptions.url
|
|
281
281
|
routeOptions.bodyLimit
|
|
282
282
|
routeOptions.logLevel
|
|
283
|
+
routeOptions.logSerializers
|
|
283
284
|
routeOptions.prefix
|
|
284
285
|
})
|
|
285
286
|
```
|
|
287
|
+
|
|
288
|
+
If you are authoring a plugin and you need to customize application routes, like modifying the options or adding new route hooks, this is the right place.
|
|
289
|
+
|
|
290
|
+
```js
|
|
291
|
+
fastify.addHook('onRoute', (routeOptions) => {
|
|
292
|
+
function onPreSerialization(request, reply, payload, done) {
|
|
293
|
+
// Your code
|
|
294
|
+
done(null, payload)
|
|
295
|
+
}
|
|
296
|
+
// preSerialization can be an array or undefined
|
|
297
|
+
routeOptions.preSerialization = [...(routeOptions.preSerialization || []), onPreSerialization]
|
|
298
|
+
})
|
|
299
|
+
```
|
|
300
|
+
|
|
286
301
|
<a name="on-register"></a>
|
|
287
302
|
### onRegister
|
|
288
303
|
Triggered when a new plugin is registered and a new encapsulation context is created. The hook will be executed **before** the registered code.<br/>
|
|
@@ -298,19 +313,22 @@ fastify.register(async (instance, opts) => {
|
|
|
298
313
|
instance.register(async (instance, opts) => {
|
|
299
314
|
instance.data.push('world')
|
|
300
315
|
console.log(instance.data) // ['hello', 'world']
|
|
301
|
-
})
|
|
302
|
-
})
|
|
316
|
+
}, { prefix: '/hola' })
|
|
317
|
+
}, { prefix: '/ciao' })
|
|
303
318
|
|
|
304
319
|
fastify.register(async (instance, opts) => {
|
|
305
320
|
console.log(instance.data) // []
|
|
306
|
-
})
|
|
321
|
+
}, { prefix: '/hello' })
|
|
307
322
|
|
|
308
|
-
fastify.addHook('onRegister', (instance) => {
|
|
323
|
+
fastify.addHook('onRegister', (instance, opts) => {
|
|
309
324
|
// Create a new array from the old one
|
|
310
325
|
// but without keeping the reference
|
|
311
326
|
// allowing the user to have encapsulated
|
|
312
327
|
// instances of the `data` property
|
|
313
328
|
instance.data = instance.data.slice()
|
|
329
|
+
|
|
330
|
+
// the options of the new registered instance
|
|
331
|
+
console.log(opts.prefix)
|
|
314
332
|
})
|
|
315
333
|
```
|
|
316
334
|
|
|
@@ -362,7 +380,7 @@ fastify.addHook('preHandler', (request, reply, done) => {
|
|
|
362
380
|
|
|
363
381
|
fastify.addHook('preSerialization', (request, reply, payload, done) => {
|
|
364
382
|
// Your code
|
|
365
|
-
done()
|
|
383
|
+
done(null, payload)
|
|
366
384
|
})
|
|
367
385
|
|
|
368
386
|
fastify.route({
|
|
@@ -396,7 +414,7 @@ fastify.route({
|
|
|
396
414
|
// done()
|
|
397
415
|
// }],
|
|
398
416
|
preSerialization: (request, reply, payload, done) => {
|
|
399
|
-
//
|
|
417
|
+
// This hook will always be executed after the shared `preSerialization` hooks
|
|
400
418
|
done(null, payload)
|
|
401
419
|
},
|
|
402
420
|
handler: function (request, reply) {
|
package/docs/Plugins.md
CHANGED
|
@@ -16,6 +16,7 @@ fastify.register(plugin, [options])
|
|
|
16
16
|
The optional `options` parameter for `fastify.register` supports a predefined set of options that Fastify itself will use, except when the plugin has been wrapped with [fastify-plugin](https://github.com/fastify/fastify-plugin). This options object will also be passed to the plugin upon invocation, regardless of whether or not the plugin has been wrapped. The currently supported list of Fastify specific options is:
|
|
17
17
|
|
|
18
18
|
+ [`logLevel`](https://github.com/fastify/fastify/blob/master/docs/Routes.md#custom-log-level)
|
|
19
|
+
+ [`logSerializers`](https://github.com/fastify/fastify/blob/master/docs/Routes.md#custom-log-serializer)
|
|
19
20
|
+ [`prefix`](https://github.com/fastify/fastify/blob/master/docs/Plugins.md#route-prefixing-options)
|
|
20
21
|
|
|
21
22
|
**Note: Those options will be ignored when used with fastify-plugin**
|
package/docs/Routes.md
CHANGED
|
@@ -1,14 +1,34 @@
|
|
|
1
1
|
<h1 align="center">Fastify</h1>
|
|
2
2
|
|
|
3
3
|
## Routes
|
|
4
|
-
|
|
4
|
+
|
|
5
|
+
The routes methods will configure the endpoints of your application.
|
|
6
|
+
You have two ways to declare a route with Fastify, the shorthand method and the full declaration.
|
|
7
|
+
|
|
8
|
+
- [Full Declaration](#full-declaration)
|
|
9
|
+
- [Route Options](#options)
|
|
10
|
+
- [Shorthand Declaration](#shorthand-declaration)
|
|
11
|
+
- [URL Parameters](#url-building)
|
|
12
|
+
- [Use `async`/`await`](#async-await)
|
|
13
|
+
- [Promise resolution](#promise-resolution)
|
|
14
|
+
- [Route Prefixing](#route-prefixing)
|
|
15
|
+
- Logs
|
|
16
|
+
- [Custom Log Level](#custom-log-level)
|
|
17
|
+
- [Custom Log Serializer](#custom-log-serializer)
|
|
18
|
+
- [Route handler configuration](#routes-config)
|
|
19
|
+
- [Route's Versioning](#version)
|
|
20
|
+
|
|
5
21
|
<a name="full-declaration"></a>
|
|
6
22
|
### Full declaration
|
|
23
|
+
|
|
7
24
|
```js
|
|
8
25
|
fastify.route(options)
|
|
9
26
|
```
|
|
10
|
-
* `method`: currently it supports `'DELETE'`, `'GET'`, `'HEAD'`, `'PATCH'`, `'POST'`, `'PUT'` and `'OPTIONS'`. It could also be an array of methods.
|
|
11
27
|
|
|
28
|
+
<a name="options"></a>
|
|
29
|
+
### Routes option
|
|
30
|
+
|
|
31
|
+
* `method`: currently it supports `'DELETE'`, `'GET'`, `'HEAD'`, `'PATCH'`, `'POST'`, `'PUT'` and `'OPTIONS'`. It could also be an array of methods.
|
|
12
32
|
* `url`: the path of the url to match this route (alias: `path`).
|
|
13
33
|
* `schema`: an object containing the schemas for the request and response.
|
|
14
34
|
They need to be in
|
|
@@ -23,14 +43,18 @@ They need to be in
|
|
|
23
43
|
* `response`: filter and generate a schema for the response, setting a
|
|
24
44
|
schema allows us to have 10-20% more throughput.
|
|
25
45
|
* `attachValidation`: attach `validationError` to request, if there is a schema validation error, instead of sending the error to the error handler.
|
|
26
|
-
* `onRequest(request, reply, done)`: a [function](https://github.com/fastify/fastify/blob/master/docs/Hooks.md#
|
|
27
|
-
* `
|
|
28
|
-
* `
|
|
29
|
-
* `
|
|
46
|
+
* `onRequest(request, reply, done)`: a [function](https://github.com/fastify/fastify/blob/master/docs/Hooks.md#onrequest) as soon that a request is received, it could also be an array of functions.
|
|
47
|
+
* `preParsing(request, reply, done)`: a [function](https://github.com/fastify/fastify/blob/master/docs/Hooks.md#preparsing) called before parsing the request, it could also be an array of functions.
|
|
48
|
+
* `preValidation(request, reply, done)`: a [function](https://github.com/fastify/fastify/blob/master/docs/Hooks.md#prevalidation) called after the shared `preValidation` hooks, useful if you need to perform authentication at route level for example, it could also be an array of functions.
|
|
49
|
+
* `preHandler(request, reply, done)`: a [function](https://github.com/fastify/fastify/blob/master/docs/Hooks.md#prehandler) called just before the request handler, it could also be an array of functions.
|
|
50
|
+
* `preSerialization(request, reply, payload, done)`: a [function](https://github.com/fastify/fastify/blob/master/docs/Hooks.md#preserialization) called just before the serialization, it could also be an array of functions.
|
|
51
|
+
* `onSend(request, reply, payload, done)`: a [function](https://github.com/fastify/fastify/blob/master/docs/Hooks.md#route-hooks) called right before a response is sent, it could also be an array of functions.
|
|
52
|
+
* `onResponse(request, reply, payload, done)`: a [function](https://github.com/fastify/fastify/blob/master/docs/Hooks.md#onresponse) called when a response has been sent, so you will not be able to send more data to the client. It could also be an array of functions.
|
|
30
53
|
* `handler(request, reply)`: the function that will handle this request.
|
|
31
54
|
* `schemaCompiler(schema)`: the function that build the schema for the validations. See [here](https://github.com/fastify/fastify/blob/master/docs/Validation-and-Serialization.md#schema-compiler)
|
|
32
55
|
* `bodyLimit`: prevents the default JSON body parser from parsing request bodies larger than this number of bytes. Must be an integer. You may also set this option globally when first creating the Fastify instance with `fastify(options)`. Defaults to `1048576` (1 MiB).
|
|
33
56
|
* `logLevel`: set log level for this route. See below.
|
|
57
|
+
* `logSerializers`: set serializers to log for this route.
|
|
34
58
|
* `config`: object used to store custom configuration.
|
|
35
59
|
* `version`: a [semver](http://semver.org/) compatible string that defined the version of the endpoint. [Example](https://github.com/fastify/fastify/blob/master/docs/Routes.md#version).
|
|
36
60
|
* `prefixTrailingSlash`: string used to determine how to handle passing `/` as a route with a prefix.
|
|
@@ -237,6 +261,7 @@ fastify.register(require('./routes/v2/users'), { prefix: '/v2' })
|
|
|
237
261
|
|
|
238
262
|
fastify.listen(3000)
|
|
239
263
|
```
|
|
264
|
+
|
|
240
265
|
```js
|
|
241
266
|
// routes/v1/users.js
|
|
242
267
|
module.exports = function (fastify, opts, done) {
|
|
@@ -244,6 +269,7 @@ module.exports = function (fastify, opts, done) {
|
|
|
244
269
|
done()
|
|
245
270
|
}
|
|
246
271
|
```
|
|
272
|
+
|
|
247
273
|
```js
|
|
248
274
|
// routes/v2/users.js
|
|
249
275
|
module.exports = function (fastify, opts, done) {
|
|
@@ -286,6 +312,7 @@ fastify.register(require('./routes/events'), { logLevel: 'debug' })
|
|
|
286
312
|
|
|
287
313
|
fastify.listen(3000)
|
|
288
314
|
```
|
|
315
|
+
|
|
289
316
|
Or you can directly pass it to a route:
|
|
290
317
|
```js
|
|
291
318
|
fastify.get('/', { logLevel: 'warn' }, (request, reply) => {
|
|
@@ -294,6 +321,64 @@ fastify.get('/', { logLevel: 'warn' }, (request, reply) => {
|
|
|
294
321
|
```
|
|
295
322
|
*Remember that the custom log level is applied only to the routes, and not to the global Fastify Logger, accessible with `fastify.log`*
|
|
296
323
|
|
|
324
|
+
<a name="custom-log-serializer"></a>
|
|
325
|
+
### Custom Log Serializer
|
|
326
|
+
|
|
327
|
+
In some context, you may need to log a large object but it could be a waste of resources for some routes. In this case, you can define some [`serializer`](https://github.com/pinojs/pino/blob/master/docs/api.md#bindingsserializers-object) and attach them in the right context!
|
|
328
|
+
|
|
329
|
+
```js
|
|
330
|
+
const fastify = require('fastify')({ logger: true })
|
|
331
|
+
|
|
332
|
+
fastify.register(require('./routes/user'), {
|
|
333
|
+
logSerializers: {
|
|
334
|
+
user: (value) => `My serializer one - ${value.name}`
|
|
335
|
+
}
|
|
336
|
+
})
|
|
337
|
+
fastify.register(require('./routes/events'), {
|
|
338
|
+
logSerializers: {
|
|
339
|
+
user: (value) => `My serializer two - ${value.name} ${value.surname}`
|
|
340
|
+
}
|
|
341
|
+
})
|
|
342
|
+
|
|
343
|
+
fastify.listen(3000)
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
You can inherit serializers by context:
|
|
347
|
+
|
|
348
|
+
```js
|
|
349
|
+
const fastify = Fastify({
|
|
350
|
+
logger: {
|
|
351
|
+
level: 'info',
|
|
352
|
+
serializers: {
|
|
353
|
+
user (req) {
|
|
354
|
+
return {
|
|
355
|
+
method: req.method,
|
|
356
|
+
url: req.url,
|
|
357
|
+
headers: req.headers,
|
|
358
|
+
hostname: req.hostname,
|
|
359
|
+
remoteAddress: req.ip,
|
|
360
|
+
remotePort: req.connection.remotePort
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
})
|
|
366
|
+
|
|
367
|
+
fastify.register(context1, {
|
|
368
|
+
logSerializers: {
|
|
369
|
+
user: value => `My serializer father - ${value}`
|
|
370
|
+
}
|
|
371
|
+
})
|
|
372
|
+
|
|
373
|
+
async function context1 (fastify, opts) {
|
|
374
|
+
fastify.get('/', (req, reply) => {
|
|
375
|
+
req.log.info({ user: 'call father serializer', key: 'another key' }) // shows: { user: 'My serializer father - call father serializer', key: 'another key' }
|
|
376
|
+
reply.send({})
|
|
377
|
+
})
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
fastify.listen(3000)
|
|
381
|
+
```
|
|
297
382
|
|
|
298
383
|
<a name="routes-config"></a>
|
|
299
384
|
### Config
|
|
@@ -315,10 +400,12 @@ fastify.listen(3000)
|
|
|
315
400
|
|
|
316
401
|
<a name="version"></a>
|
|
317
402
|
### Version
|
|
403
|
+
|
|
318
404
|
#### Default
|
|
319
405
|
If needed you can provide a version option, which will allow you to declare multiple versions of the same route. The versioning should follow the [semver](http://semver.org/) specification.<br/>
|
|
320
406
|
Fastify will automatically detect the `Accept-Version` header and route the request accordingly (advanced ranges and pre-releases currently are not supported).<br/>
|
|
321
407
|
*Be aware that using this feature will cause a degradation of the overall performances of the router.*
|
|
408
|
+
|
|
322
409
|
```js
|
|
323
410
|
fastify.route({
|
|
324
411
|
method: 'GET',
|
|
@@ -339,7 +426,9 @@ fastify.inject({
|
|
|
339
426
|
// { hello: 'world' }
|
|
340
427
|
})
|
|
341
428
|
```
|
|
429
|
+
|
|
342
430
|
If you declare multiple versions with the same major or minor, Fastify will always choose the highest compatible with the `Accept-Version` header value.<br/>
|
|
343
431
|
If the request will not have the `Accept-Version` header, a 404 error will be returned.
|
|
432
|
+
|
|
344
433
|
#### Custom
|
|
345
434
|
It's possible to define a custom versioning logic. This can be done through the [`versioning`](https://github.com/fastify/fastify/blob/master/docs/Server.md#versioning) configuration, when creating a fastify server instance.
|
package/docs/Server.md
CHANGED
|
@@ -75,7 +75,7 @@ Defines the maximum payload, in bytes, the server is allowed to accept.
|
|
|
75
75
|
|
|
76
76
|
Defines what action the framework must take when parsing a JSON object
|
|
77
77
|
with `__proto__`. This functionality is provided by
|
|
78
|
-
[
|
|
78
|
+
[secure-json-parse](https://github.com/fastify/secure-json-parse).
|
|
79
79
|
See https://hueniverse.com/a-tale-of-prototype-poisoning-2610fa170061
|
|
80
80
|
for more details about prototype poisoning attacks.
|
|
81
81
|
|
|
@@ -83,6 +83,19 @@ Possible values are `'error'`, `'remove'` and `'ignore'`.
|
|
|
83
83
|
|
|
84
84
|
+ Default: `'error'`
|
|
85
85
|
|
|
86
|
+
<a name="factory-on-constructor-poisoning"></a>
|
|
87
|
+
### `onConstructorPoisoning`
|
|
88
|
+
|
|
89
|
+
Defines what action the framework must take when parsing a JSON object
|
|
90
|
+
with `constructor`. This functionality is provided by
|
|
91
|
+
[secure-json-parse](https://github.com/fastify/secure-json-parse).
|
|
92
|
+
See https://hueniverse.com/a-tale-of-prototype-poisoning-2610fa170061
|
|
93
|
+
for more details about prototype poisoning attacks.
|
|
94
|
+
|
|
95
|
+
Possible values are `'error'`, `'remove'` and `'ignore'`.
|
|
96
|
+
|
|
97
|
+
+ Default: `'ignore'`
|
|
98
|
+
|
|
86
99
|
<a name="factory-logger"></a>
|
|
87
100
|
### `logger`
|
|
88
101
|
|
|
@@ -360,6 +373,42 @@ If `false`, the server routes the incoming request as usual.
|
|
|
360
373
|
|
|
361
374
|
+ Default: `true`
|
|
362
375
|
|
|
376
|
+
<a name="factory-ajv"></a>
|
|
377
|
+
### `ajv`
|
|
378
|
+
|
|
379
|
+
Configure the ajv instance used by Fastify without providing a custom one.
|
|
380
|
+
|
|
381
|
+
+ Default:
|
|
382
|
+
|
|
383
|
+
```js
|
|
384
|
+
{
|
|
385
|
+
customOptions: {
|
|
386
|
+
removeAdditional: true,
|
|
387
|
+
useDefaults: true,
|
|
388
|
+
coerceTypes: true,
|
|
389
|
+
allErrors: true,
|
|
390
|
+
nullable: true
|
|
391
|
+
},
|
|
392
|
+
plugins: []
|
|
393
|
+
}
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
```js
|
|
397
|
+
const fastify = require('fastify')({
|
|
398
|
+
ajv: {
|
|
399
|
+
customOptions: {
|
|
400
|
+
nullable: false // Refer to [ajv options](https://ajv.js.org/#options)
|
|
401
|
+
},
|
|
402
|
+
plugins: [
|
|
403
|
+
require('ajv-merge-patch')
|
|
404
|
+
[require('ajv-keywords'), 'instanceof'];
|
|
405
|
+
// Usage: [plugin, pluginOptions] - Plugin with options
|
|
406
|
+
// Usage: plugin - Plugin without options
|
|
407
|
+
]
|
|
408
|
+
}
|
|
409
|
+
})
|
|
410
|
+
```
|
|
411
|
+
|
|
363
412
|
## Instance
|
|
364
413
|
|
|
365
414
|
### Server Methods
|
package/docs/TypeScript.md
CHANGED
|
@@ -21,6 +21,7 @@ import { Server, IncomingMessage, ServerResponse } from 'http'
|
|
|
21
21
|
// Create a http server. We pass the relevant typings for our http version used.
|
|
22
22
|
// By passing types we get correctly typed access to the underlying http objects in routes.
|
|
23
23
|
// If using http2 we'd pass <http2.Http2Server, http2.Http2ServerRequest, http2.Http2ServerResponse>
|
|
24
|
+
// For https pass http2.Http2SecureServer or http.SecureServer instead of Server.
|
|
24
25
|
const server: fastify.FastifyInstance<Server, IncomingMessage, ServerResponse> = fastify({})
|
|
25
26
|
|
|
26
27
|
const opts: fastify.RouteShorthandOptions = {
|
|
@@ -218,26 +219,43 @@ Typings for many plugins that extend the `FastifyRequest`, `FastifyReply` or `Fa
|
|
|
218
219
|
This code shows the typings for the `fastify-static` plugin.
|
|
219
220
|
|
|
220
221
|
```ts
|
|
222
|
+
/// <reference types="node" />
|
|
223
|
+
|
|
221
224
|
// require fastify typings
|
|
222
|
-
import fastify
|
|
223
|
-
|
|
225
|
+
import * as fastify from 'fastify';
|
|
226
|
+
|
|
227
|
+
// require necessary http, http2, https typings
|
|
224
228
|
import { Server, IncomingMessage, ServerResponse } from "http";
|
|
229
|
+
import { Http2SecureServer, Http2Server, Http2ServerRequest, Http2ServerResponse } from "http2";
|
|
230
|
+
import * as https from "https";
|
|
231
|
+
|
|
232
|
+
type HttpServer = Server | Http2Server | Http2SecureServer | https.Server;
|
|
233
|
+
type HttpRequest = IncomingMessage | Http2ServerRequest;
|
|
234
|
+
type HttpResponse = ServerResponse | Http2ServerResponse;
|
|
225
235
|
|
|
226
236
|
// extend fastify typings
|
|
227
237
|
declare module "fastify" {
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
238
|
+
interface FastifyReply<HttpResponse> {
|
|
239
|
+
sendFile(filename: string): FastifyReply<HttpResponse>;
|
|
240
|
+
}
|
|
231
241
|
}
|
|
232
242
|
|
|
233
243
|
// declare plugin type using fastify.Plugin
|
|
234
|
-
declare
|
|
244
|
+
declare function fastifyStatic(): fastify.Plugin<
|
|
245
|
+
Server,
|
|
246
|
+
IncomingMessage,
|
|
247
|
+
ServerResponse,
|
|
248
|
+
{
|
|
235
249
|
root: string;
|
|
236
250
|
prefix?: string;
|
|
237
251
|
serve?: boolean;
|
|
238
252
|
decorateReply?: boolean;
|
|
239
253
|
schemaHide?: boolean;
|
|
240
254
|
setHeaders?: (...args: any[]) => void;
|
|
255
|
+
redirect?: boolean;
|
|
256
|
+
wildcard?: boolean | string;
|
|
257
|
+
|
|
258
|
+
// Passed on to `send`
|
|
241
259
|
acceptRanges?: boolean;
|
|
242
260
|
cacheControl?: boolean;
|
|
243
261
|
dotfiles?: boolean;
|
|
@@ -247,7 +265,12 @@ declare const fastifyStatic: fastify.Plugin<Server, IncomingMessage, ServerRespo
|
|
|
247
265
|
index?: string[];
|
|
248
266
|
lastModified?: boolean;
|
|
249
267
|
maxAge?: string | number;
|
|
250
|
-
}
|
|
268
|
+
}
|
|
269
|
+
>;
|
|
270
|
+
|
|
271
|
+
declare namespace fastifyStatic {
|
|
272
|
+
interface FastifyStaticOptions {}
|
|
273
|
+
}
|
|
251
274
|
|
|
252
275
|
// export plugin type
|
|
253
276
|
export = fastifyStatic;
|
|
@@ -240,6 +240,77 @@ This example will returns:
|
|
|
240
240
|
| /sub | one, two |
|
|
241
241
|
| /deep | one, two, three |
|
|
242
242
|
|
|
243
|
+
<a name="ajv-plugins"></a>
|
|
244
|
+
#### Ajv Plugins
|
|
245
|
+
|
|
246
|
+
You can provide a list of plugins you want to use with Ajv:
|
|
247
|
+
|
|
248
|
+
> Refer to [`ajv options`](https://github.com/fastify/fastify/blob/master/docs/Server.md#factory-ajv) to check plugins format
|
|
249
|
+
|
|
250
|
+
```js
|
|
251
|
+
const fastify = require('fastify')({
|
|
252
|
+
ajv: {
|
|
253
|
+
plugins: [
|
|
254
|
+
require('ajv-merge-patch')
|
|
255
|
+
]
|
|
256
|
+
}
|
|
257
|
+
})
|
|
258
|
+
|
|
259
|
+
fastify.route({
|
|
260
|
+
method: 'POST',
|
|
261
|
+
url: '/',
|
|
262
|
+
schema: {
|
|
263
|
+
body: {
|
|
264
|
+
$patch: {
|
|
265
|
+
source: {
|
|
266
|
+
type: 'object',
|
|
267
|
+
properties: {
|
|
268
|
+
q: {
|
|
269
|
+
type: 'string'
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
},
|
|
273
|
+
with: [
|
|
274
|
+
{
|
|
275
|
+
op: 'add',
|
|
276
|
+
path: '/properties/q',
|
|
277
|
+
value: { type: 'number' }
|
|
278
|
+
}
|
|
279
|
+
]
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
},
|
|
283
|
+
handler (req, reply) {
|
|
284
|
+
reply.send({ ok: 1 })
|
|
285
|
+
}
|
|
286
|
+
})
|
|
287
|
+
|
|
288
|
+
fastify.route({
|
|
289
|
+
method: 'POST',
|
|
290
|
+
url: '/',
|
|
291
|
+
schema: {
|
|
292
|
+
body: {
|
|
293
|
+
$merge: {
|
|
294
|
+
source: {
|
|
295
|
+
type: 'object',
|
|
296
|
+
properties: {
|
|
297
|
+
q: {
|
|
298
|
+
type: 'string'
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
},
|
|
302
|
+
with: {
|
|
303
|
+
required: ['q']
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
},
|
|
308
|
+
handler (req, reply) {
|
|
309
|
+
reply.send({ ok: 1 })
|
|
310
|
+
}
|
|
311
|
+
})
|
|
312
|
+
```
|
|
313
|
+
|
|
243
314
|
<a name="schema-compiler"></a>
|
|
244
315
|
#### Schema Compiler
|
|
245
316
|
|
|
@@ -257,7 +328,9 @@ Fastify's [baseline ajv configuration](https://github.com/epoberezkin/ajv#option
|
|
|
257
328
|
}
|
|
258
329
|
```
|
|
259
330
|
|
|
260
|
-
This baseline configuration
|
|
331
|
+
This baseline configuration can be modified by providing [`ajv.customOptions`](https://github.com/fastify/fastify/blob/master/docs/Server.md#factory-ajv) to your Fastify factory.
|
|
332
|
+
|
|
333
|
+
If you want to change or set additional config options, you will need to create your own instance and override the existing one like:
|
|
261
334
|
|
|
262
335
|
```js
|
|
263
336
|
const fastify = require('fastify')()
|