fastify 3.17.0 → 3.19.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.
- package/GOVERNANCE.md +1 -1
- package/README.md +0 -4
- package/build/build-validation.js +2 -0
- package/docs/ContentTypeParser.md +2 -0
- package/docs/Ecosystem.md +7 -1
- package/docs/Errors.md +2 -0
- package/docs/Getting-Started.md +2 -0
- package/docs/Hooks.md +1 -1
- package/docs/LTS.md +3 -2
- package/docs/Routes.md +5 -0
- package/docs/Server.md +63 -5
- package/docs/TypeScript.md +9 -1
- package/docs/Validation-and-Serialization.md +1 -1
- package/fastify.d.ts +4 -3
- package/fastify.js +24 -22
- package/lib/configValidator.js +218 -185
- package/lib/handleRequest.js +6 -0
- package/lib/hooks.js +2 -1
- package/lib/pluginUtils.js +1 -3
- package/lib/request.js +1 -1
- package/lib/route.js +2 -2
- package/lib/schemas.js +8 -8
- package/package.json +6 -11
- package/test/close.test.js +11 -14
- package/test/internals/initialConfig.test.js +2 -0
- package/test/internals/validation.test.js +21 -6
- package/test/pretty-print.test.js +89 -0
- package/test/reply-error.test.js +53 -0
- package/test/throw.test.js +12 -0
- package/test/types/fastify.test-d.ts +14 -3
- package/test/types/hooks.test-d.ts +41 -17
- package/test/types/logger.test-d.ts +7 -0
- package/test/versioned-routes.test.js +1 -1
- package/types/hooks.d.ts +23 -1
- package/types/logger.d.ts +5 -0
- package/test/internals/version.test.js +0 -43
package/GOVERNANCE.md
CHANGED
|
@@ -80,7 +80,7 @@ The consensus to grant a new candidate Collaborator status is reached when:
|
|
|
80
80
|
- at least one of the Lead Maintainers approve
|
|
81
81
|
- at least two of the Team Members approve
|
|
82
82
|
|
|
83
|
-
After these conditions are satisfied, the [onboarding process](#onboarding-collaborators) may start.
|
|
83
|
+
After these conditions are satisfied, the [onboarding process](CONTRIBUTING.md#onboarding-collaborators) may start.
|
|
84
84
|
|
|
85
85
|
|
|
86
86
|
## Lead Maintainers nominations
|
package/README.md
CHANGED
|
@@ -30,10 +30,6 @@ How can you efficiently handle the resources of your server, knowing that you ar
|
|
|
30
30
|
|
|
31
31
|
Enter Fastify. Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture. It is inspired by Hapi and Express and as far as we know, it is one of the fastest web frameworks in town.
|
|
32
32
|
|
|
33
|
-
### Requirements
|
|
34
|
-
|
|
35
|
-
Node.js v10 LTS (10.16.0) or later.
|
|
36
|
-
|
|
37
33
|
### Quick start
|
|
38
34
|
|
|
39
35
|
Create a folder and make it your current working directory:
|
|
@@ -18,6 +18,7 @@ const defaultInitOptions = {
|
|
|
18
18
|
bodyLimit: 1024 * 1024, // 1 MiB
|
|
19
19
|
caseSensitive: true,
|
|
20
20
|
disableRequestLogging: false,
|
|
21
|
+
jsonShorthand: true,
|
|
21
22
|
ignoreTrailingSlash: false,
|
|
22
23
|
maxParamLength: 100,
|
|
23
24
|
onProtoPoisoning: 'error',
|
|
@@ -73,6 +74,7 @@ const schema = {
|
|
|
73
74
|
type: 'boolean',
|
|
74
75
|
default: false
|
|
75
76
|
},
|
|
77
|
+
jsonShorthand: { type: 'boolean', default: defaultInitOptions.jsonShorthand },
|
|
76
78
|
maxParamLength: { type: 'integer', default: defaultInitOptions.maxParamLength },
|
|
77
79
|
onProtoPoisoning: { type: 'string', default: defaultInitOptions.onProtoPoisoning },
|
|
78
80
|
onConstructorPoisoning: { type: 'string', default: defaultInitOptions.onConstructorPoisoning },
|
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
## `Content-Type` Parser
|
|
4
4
|
Natively, Fastify only supports `'application/json'` and `'text/plain'` content types. The default charset is `utf-8`. If you need to support different content types, you can use the `addContentTypeParser` API. *The default JSON and/or plain text parser can be changed.*
|
|
5
5
|
|
|
6
|
+
*Note: If you decide to specify your own content type with the `Content-Type` header, UTF-8 will not be the default. Be sure to include UTF-8 like this `text/html; charset=utf-8`.*
|
|
7
|
+
|
|
6
8
|
As with the other APIs, `addContentTypeParser` is encapsulated in the scope in which it is declared. This means that if you declare it in the root scope it will be available everywhere, while if you declare it inside a plugin it will be available only in that scope and its children.
|
|
7
9
|
|
|
8
10
|
Fastify automatically adds the parsed request payload to the [Fastify request](Request.md) object which you can access with `request.body`.
|
package/docs/Ecosystem.md
CHANGED
|
@@ -53,6 +53,7 @@ Plugins maintained by the Fastify team are listed under [Core](#core) while plug
|
|
|
53
53
|
|
|
54
54
|
#### [Community](#community)
|
|
55
55
|
|
|
56
|
+
- [`@applicazza/fastify-nextjs`](https://github.com/applicazza/fastify-nextjs) Alternate Fastify and Next.js integration.
|
|
56
57
|
- [`@coobaha/typed-fastify`](https://github.com/Coobaha/typed-fastify) Strongly typed routes with a runtime validation using JSON schema generated from types.
|
|
57
58
|
- [`@dnlup/fastify-doc`](https://github.com/dnlup/fastify-doc) A plugin for sampling process metrics.
|
|
58
59
|
- [`@dnlup/fastify-traps`](https://github.com/dnlup/fastify-traps) A plugin to close the server gracefully on `SIGINT` and `SIGTERM` signals.
|
|
@@ -63,6 +64,7 @@ Plugins maintained by the Fastify team are listed under [Core](#core) while plug
|
|
|
63
64
|
- [`@mgcrea/fastify-session-sodium-crypto`](https://github.com/mgcrea/fastify-session-sodium-crypto) Fast sodium-based crypto for @mgcrea/fastify-session
|
|
64
65
|
- [`@mgcrea/fastify-session`](https://github.com/mgcrea/fastify-session) Session plugin for Fastify that supports both stateless and stateful sessions
|
|
65
66
|
- [`@mgcrea/pino-pretty-compact`](https://github.com/mgcrea/pino-pretty-compact) A custom compact pino-base prettifier
|
|
67
|
+
- [`@trubavuong/fastify-seaweedfs`](https://github.com/trubavuong/fastify-seaweedfs) SeaweedFS for Fastify
|
|
66
68
|
- [`apollo-server-fastify`](https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-fastify) Run an [Apollo Server](https://github.com/apollographql/apollo-server) to serve GraphQL with Fastify.
|
|
67
69
|
- [`arecibo`](https://github.com/nucleode/arecibo) Fastify ping responder for Kubernetes Liveness and Readiness Probes.
|
|
68
70
|
- [`cls-rtracer`](https://github.com/puzpuzpuz/cls-rtracer) Fastify middleware for CLS-based request ID generation. An out-of-the-box solution for adding request IDs into your logs.
|
|
@@ -75,6 +77,7 @@ Plugins maintained by the Fastify team are listed under [Core](#core) while plug
|
|
|
75
77
|
- [`fastify-autoroutes`](https://github.com/GiovanniCardamone/fastify-autoroutes) Plugin to scan and load routes based on filesystem path from a custom directory.
|
|
76
78
|
- [`fastify-axios`](https://github.com/davidedantonio/fastify-axios) Plugin to send HTTP requests via [axios](https://github.com/axios/axios).
|
|
77
79
|
- [`fastify-babel`](https://github.com/cfware/fastify-babel) Fastify plugin for development servers that require Babel transformations of JavaScript sources.
|
|
80
|
+
- [`fastify-bcrypt`](https://github.com/heply/fastify-bcrypt) A Bcrypt hash generator & checker.
|
|
78
81
|
- [`fastify-blipp`](https://github.com/PavelPolyakov/fastify-blipp) Prints your routes to the console, so you definitely know which endpoints are available.
|
|
79
82
|
- [`fastify-bookshelf`](https://github.com/butlerx/fastify-bookshelfjs) Fastify plugin to add [bookshelf.js](https://bookshelfjs.org/) ORM support.
|
|
80
83
|
- [`fastify-boom`](https://github.com/jeromemacias/fastify-boom) Fastify plugin to add [boom](https://github.com/hapijs/boom) support.
|
|
@@ -89,6 +92,7 @@ Plugins maintained by the Fastify team are listed under [Core](#core) while plug
|
|
|
89
92
|
- [`fastify-disablecache`](https://github.com/Fdawgs/fastify-disablecache) Fastify plugin to disable client-side caching, inspired by [nocache](https://github.com/helmetjs/nocache).
|
|
90
93
|
- [`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.
|
|
91
94
|
- [`fastify-dynareg`](https://github.com/greguz/fastify-dynareg) Dynamic plugin register for Fastify.
|
|
95
|
+
- [`fastify-early-hints`](https://github.com/zekth/fastify-early-hints) Plugin to add HTTP 103 feature based on [RFC 8297](https://httpwg.org/specs/rfc8297.html)
|
|
92
96
|
- [`fastify-envalid`](https://github.com/alemagio/fastify-envalid) Fastify plugin to integrate [envalid](https://github.com/af/envalid) in your Fastify project.
|
|
93
97
|
- [`fastify-error-page`](https://github.com/hemerajs/fastify-error-page) Fastify plugin to print errors in structured HTML to the browser.
|
|
94
98
|
- [`fastify-esso`](https://github.com/patrickpissurno/fastify-esso) The easiest authentication plugin for Fastify, with built-in support for Single sign-on (and great documentation).
|
|
@@ -98,6 +102,7 @@ Plugins maintained by the Fastify team are listed under [Core](#core) while plug
|
|
|
98
102
|
- [`fastify-file-upload`](https://github.com/huangang/fastify-file-upload) Fastify plugin for uploading files.
|
|
99
103
|
- [`fastify-firebase`](https://github.com/now-ims/fastify-firebase) Fastify plugin for [Firebase Admin SDK](https://firebase.google.com/docs/admin/setup) to Fastify so you can easily use Firebase Auth, Firestore, Cloud Storage, Cloud Messaging, and more.
|
|
100
104
|
- [`fastify-firebase-auth`](https://github.com/oxsav/fastify-firebase-auth) Firebase Authentication for Fastify supporting all of the methods relating to the authentication API.
|
|
105
|
+
- [`fastify-formidable`](https://github.com/climba03003/fastify-formidable) Handy plugin to provide multipart support and fastify-swagger integration.
|
|
101
106
|
- [`fastify-gcloud-trace`](https://github.com/mkinoshi/fastify-gcloud-trace) [Google Cloud Trace API](https://cloud.google.com/trace/docs/reference) Connector for Fastify.
|
|
102
107
|
- [`fastify-get-head`](https://github.com/MetCoder95/fastify-get-head) Small plugin to set a new HEAD route handler for each GET route previously registered in Fastify.
|
|
103
108
|
- [`fastify-good-sessions`](https://github.com/Phara0h/fastify-good-sessions) A good Fastify sessions plugin focused on speed.
|
|
@@ -144,7 +149,7 @@ Plugins maintained by the Fastify team are listed under [Core](#core) while plug
|
|
|
144
149
|
- [`fastify-objectionjs-classes`](https://github.com/kamikazechaser/fastify-objectionjs-classes) Plugin to cherry-pick classes from objectionjs ORM.
|
|
145
150
|
- [`fastify-openapi-docs`](https://github.com/ShogunPanda/fastify-openapi-docs) A Fastify plugin that generates OpenAPI spec automatically.
|
|
146
151
|
- [`fastify-openapi-glue`](https://github.com/seriousme/fastify-openapi-glue) Glue for OpenAPI specifications in Fastify, autogenerates routes based on an OpenAPI Specification.
|
|
147
|
-
- [`fastify-opentelemetry`](https://github.com/autotelic/fastify-opentelemetry) A Fastify plugin that uses the [OpenTelemetry API](https://github.com/open-telemetry/opentelemetry-js
|
|
152
|
+
- [`fastify-opentelemetry`](https://github.com/autotelic/fastify-opentelemetry) A Fastify plugin that uses the [OpenTelemetry API](https://github.com/open-telemetry/opentelemetry-js-api) to provide request tracing.
|
|
148
153
|
- [`fastify-oracle`](https://github.com/cemremengu/fastify-oracle) Attaches an [`oracledb`](https://github.com/oracle/node-oracledb) connection pool to a Fastify server instance.
|
|
149
154
|
- [`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.
|
|
150
155
|
- [`fastify-piscina`](https://github.com/piscinajs/fastify-piscina) A worker thread pool plugin using [Piscina](https://github.com/piscinajs/piscina).
|
|
@@ -164,6 +169,7 @@ Plugins maintained by the Fastify team are listed under [Core](#core) while plug
|
|
|
164
169
|
- [`fastify-resty`](https://github.com/FastifyResty/fastify-resty) Fastify-based web framework with REST API routes auto-generation for TypeORM entities using DI and decorators.
|
|
165
170
|
- [`fastify-reverse-routes`](https://github.com/dimonnwc3/fastify-reverse-routes) Fastify reverse routes plugin, allows to defined named routes and build path using name and parameters.
|
|
166
171
|
- [`fastify-rob-config`](https://github.com/jeromemacias/fastify-rob-config) Fastify Rob-Config integration.
|
|
172
|
+
- [`fastify-route-group`](https://github.com/TakNePoidet/fastify-route-group) Convenient grouping and inheritance of routes
|
|
167
173
|
- [`fastify-schema-constraint`](https://github.com/Eomm/fastify-schema-constraint) Choose the JSON schema to use based on request parameters.
|
|
168
174
|
- [`fastify-schema-to-typescript`](https://github.com/thomasthiebaud/fastify-schema-to-typescript) Generate typescript types based on your JSON/YAML validation schemas so they are always in sync.
|
|
169
175
|
- [`fastify-secure-session`](https://github.com/mcollina/fastify-secure-session) Create a secure stateless cookie session for Fastify.
|
package/docs/Errors.md
CHANGED
|
@@ -68,6 +68,8 @@ The parser for this content type was already registered.
|
|
|
68
68
|
|
|
69
69
|
The request body is larger than the provided limit.
|
|
70
70
|
|
|
71
|
+
This setting can be defined in the Fastify server instance: [`bodyLimit`](Server.md#bodyLimit)
|
|
72
|
+
|
|
71
73
|
<a name="FST_ERR_CTP_EMPTY_TYPE"></a>
|
|
72
74
|
#### FST_ERR_CTP_EMPTY_TYPE
|
|
73
75
|
|
package/docs/Getting-Started.md
CHANGED
|
@@ -242,6 +242,8 @@ As discussed previously, Fastify offers a solid encapsulation model, to help you
|
|
|
242
242
|
### Validate your data
|
|
243
243
|
Data validation is extremely important and a core concept of the framework.<br>
|
|
244
244
|
To validate incoming requests, Fastify uses [JSON Schema](https://json-schema.org/).
|
|
245
|
+
(JTD schemas are loosely supported, but `jsonShorthand` must be disabled first)
|
|
246
|
+
|
|
245
247
|
Let's look at an example demonstrating validation for routes:
|
|
246
248
|
```js
|
|
247
249
|
const opts = {
|
package/docs/Hooks.md
CHANGED
|
@@ -321,7 +321,7 @@ You can hook into the application-lifecycle as well.
|
|
|
321
321
|
- [onRegister](#onregister)
|
|
322
322
|
|
|
323
323
|
### onReady
|
|
324
|
-
Triggered before the server starts listening for requests. It cannot change the routes or add new hooks.
|
|
324
|
+
Triggered before the server starts listening for requests and when `.ready()` is invoked. It cannot change the routes or add new hooks.
|
|
325
325
|
Registered hook functions are executed serially.
|
|
326
326
|
Only after all `onReady` hook functions have completed will the server start listening for requests.
|
|
327
327
|
Hook functions accept one argument: a callback, `done`, to be invoked after the hook function is complete.
|
package/docs/LTS.md
CHANGED
|
@@ -19,9 +19,10 @@ out in this document:
|
|
|
19
19
|
e.g. minimum supported Node.js version.
|
|
20
20
|
|
|
21
21
|
1. Major releases will be tested and verified against all Node.js
|
|
22
|
-
|
|
22
|
+
release lines that are supported by the
|
|
23
23
|
[Node.js LTS policy](https://github.com/nodejs/Release) within the
|
|
24
|
-
LTS period of that given Fastify release line.
|
|
24
|
+
LTS period of that given Fastify release line. This implies that only
|
|
25
|
+
the latest Node.js release of a given line is supported.
|
|
25
26
|
|
|
26
27
|
A "month" is defined as 30 consecutive days.
|
|
27
28
|
|
package/docs/Routes.md
CHANGED
|
@@ -69,6 +69,11 @@ They need to be in
|
|
|
69
69
|
|
|
70
70
|
`reply` is defined in [Reply](Reply.md).
|
|
71
71
|
|
|
72
|
+
**Notice:** The documentation of `onRequest`, `preParsing`, `preValidation`,
|
|
73
|
+
`preHandler`, `preSerialization`, `onSend`, and `onResponse` are described in
|
|
74
|
+
more detail in [Hooks](Hooks.md). Additionally, to send a response before the
|
|
75
|
+
request is handled by the `handler` please refer to
|
|
76
|
+
[Respond to a request from a hook](Hooks.md#respond-to-a-request-from-a-hook).
|
|
72
77
|
|
|
73
78
|
Example:
|
|
74
79
|
```js
|
package/docs/Server.md
CHANGED
|
@@ -218,6 +218,37 @@ fastify.listen(3000)
|
|
|
218
218
|
|
|
219
219
|
Internally Fastify uses the API of Node core HTTP server, so if you are using a custom server you must be sure to have the same API exposed. If not, you can enhance the server instance inside the `serverFactory` function before the `return` statement.<br/>
|
|
220
220
|
|
|
221
|
+
<a name="schema-json-shorthand"></a>
|
|
222
|
+
### `jsonShorthand`
|
|
223
|
+
|
|
224
|
+
+ Default: `true`
|
|
225
|
+
|
|
226
|
+
Internally, and by default, Fastify will automatically infer the root properties of JSON Schemas if it doesn't find valid root properties according to the JSON Schema spec. If you wish to implement your own schema validation compiler, for example: to parse schemas as JTD instead of JSON Schema, then you can explicitly set this option to `false` to make sure the schemas you receive are unmodified and are not being treated internally as JSON Schema.
|
|
227
|
+
|
|
228
|
+
```js
|
|
229
|
+
const AjvJTD = require('ajv/dist/jtd'/* only valid for AJV v7+ */)
|
|
230
|
+
const ajv = new AjvJTD({
|
|
231
|
+
// This would let you throw at start for invalid JTD schema objects
|
|
232
|
+
allErrors: process.env.NODE_ENV === 'development'
|
|
233
|
+
})
|
|
234
|
+
const fastify = Fastify({ jsonShorthand: false })
|
|
235
|
+
fastify.setValidatorCompiler(({ schema }) => {
|
|
236
|
+
return ajv.compile(schema)
|
|
237
|
+
})
|
|
238
|
+
fastify.post('/', {
|
|
239
|
+
schema: {
|
|
240
|
+
body: {
|
|
241
|
+
properties: {
|
|
242
|
+
foo: { type: 'uint8' }
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
handler (req, reply) { reply.send({ ok: 1 }) }
|
|
247
|
+
})
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
**Note: Fastify does not currently throw on invalid schemas, so if you turn this off in an existing project, you need to be careful that none of your existing schemas become invalid as a result, since they will be treated as a catch-all.**
|
|
251
|
+
|
|
221
252
|
<a name="factory-case-sensitive"></a>
|
|
222
253
|
### `caseSensitive`
|
|
223
254
|
|
|
@@ -232,7 +263,7 @@ fastify.get('/user/:username', (request, reply) => {
|
|
|
232
263
|
})
|
|
233
264
|
```
|
|
234
265
|
|
|
235
|
-
Please note
|
|
266
|
+
Please note that setting this option to `false` goes against
|
|
236
267
|
[RFC3986](https://tools.ietf.org/html/rfc3986#section-6.2.2.1).
|
|
237
268
|
|
|
238
269
|
<a name="factory-request-id-header"></a>
|
|
@@ -288,7 +319,7 @@ const fastify = Fastify({ trustProxy: true })
|
|
|
288
319
|
}
|
|
289
320
|
```
|
|
290
321
|
|
|
291
|
-
For more examples, refer to the [
|
|
322
|
+
For more examples, refer to the [`proxy-addr`](https://www.npmjs.com/package/proxy-addr) package.
|
|
292
323
|
|
|
293
324
|
You may access the `ip`, `ips`, `hostname` and `protocol` values on the [`request`](Request.md) object.
|
|
294
325
|
|
|
@@ -967,6 +998,8 @@ fastify.register(function (instance, options, done) {
|
|
|
967
998
|
}, { prefix: '/v1' })
|
|
968
999
|
```
|
|
969
1000
|
|
|
1001
|
+
Fastify calls setNotFoundHandler to add a default 404 handler at startup before plugins are registered. If you would like to augment the behavior of the default 404 handler, for example with plugins, you can call setNotFoundHandler with no arguments `fastify.setNotFoundHandler()` within the context of these registered plugins.
|
|
1002
|
+
|
|
970
1003
|
<a name="set-error-handler"></a>
|
|
971
1004
|
#### setErrorHandler
|
|
972
1005
|
|
|
@@ -1026,6 +1059,31 @@ fastify.ready(() => {
|
|
|
1026
1059
|
})
|
|
1027
1060
|
```
|
|
1028
1061
|
|
|
1062
|
+
`fastify.printRoutes({ includeMeta: (true | []) })` will display properties from the `route.store` object for each displayed route. This can be an `array` of keys (e.g. `['onRequest', Symbol('key')]`), or `true` to display all properties. A shorthand option, `fastify.printRoutes({ includeHooks: true })` will include all [hooks](https://www.fastify.io/docs/latest/Hooks/).
|
|
1063
|
+
|
|
1064
|
+
```js
|
|
1065
|
+
console.log(fastify.printRoutes({ includeHooks: true, includeMeta: ['metaProperty'] }))
|
|
1066
|
+
// └── /
|
|
1067
|
+
// ├── test (GET)
|
|
1068
|
+
// │ • (onRequest) ["anonymous()","namedFunction()"]
|
|
1069
|
+
// │ • (metaProperty) "value"
|
|
1070
|
+
// │ └── /hello (GET)
|
|
1071
|
+
// └── hel
|
|
1072
|
+
// ├── lo/world (GET)
|
|
1073
|
+
// │ • (onTimeout) ["anonymous()"]
|
|
1074
|
+
// └── licopter (GET)
|
|
1075
|
+
|
|
1076
|
+
console.log(fastify.printRoutes({ includeHooks: true }))
|
|
1077
|
+
// └── /
|
|
1078
|
+
// ├── test (GET)
|
|
1079
|
+
// │ • (onRequest) ["anonymous()","namedFunction()"]
|
|
1080
|
+
// │ └── /hello (GET)
|
|
1081
|
+
// └── hel
|
|
1082
|
+
// ├── lo/world (GET)
|
|
1083
|
+
// │ • (onTimeout) ["anonymous()"]
|
|
1084
|
+
// └── licopter (GET)
|
|
1085
|
+
```
|
|
1086
|
+
|
|
1029
1087
|
<a name="print-plugins"></a>
|
|
1030
1088
|
#### printPlugins
|
|
1031
1089
|
|
|
@@ -1042,9 +1100,9 @@ fastify.ready(() => {
|
|
|
1042
1100
|
console.error(fastify.printPlugins())
|
|
1043
1101
|
// will output the following to stderr:
|
|
1044
1102
|
// └── root
|
|
1045
|
-
//
|
|
1046
|
-
//
|
|
1047
|
-
//
|
|
1103
|
+
// ├── foo
|
|
1104
|
+
// │ └── bar
|
|
1105
|
+
// └── baz
|
|
1048
1106
|
})
|
|
1049
1107
|
```
|
|
1050
1108
|
|
package/docs/TypeScript.md
CHANGED
|
@@ -265,6 +265,11 @@ In the last example we used interfaces to define the types for the request query
|
|
|
265
265
|
const { username, password } = request.query
|
|
266
266
|
done(username !== 'admin' ? new Error('Must be admin') : undefined)
|
|
267
267
|
}
|
|
268
|
+
// or if using async
|
|
269
|
+
// preValidation: async (request, reply) => {
|
|
270
|
+
// const { username, password } = request.query
|
|
271
|
+
// return username !== "admin" ? new Error("Must be admin") : undefined;
|
|
272
|
+
// }
|
|
268
273
|
}, async (request, reply) => {
|
|
269
274
|
const customerHeader = request.headers['h-Custom']
|
|
270
275
|
// do something with request data
|
|
@@ -281,13 +286,15 @@ In the last example we used interfaces to define the types for the request query
|
|
|
281
286
|
querystring: QuerystringSchema,
|
|
282
287
|
headers: HeadersSchema
|
|
283
288
|
},
|
|
284
|
-
preHandler: (request, reply) => {
|
|
289
|
+
preHandler: (request, reply, done) => {
|
|
285
290
|
const { username, password } = request.query
|
|
286
291
|
const customerHeader = request.headers['h-Custom']
|
|
292
|
+
done()
|
|
287
293
|
},
|
|
288
294
|
handler: (request, reply) => {
|
|
289
295
|
const { username, password } = request.query
|
|
290
296
|
const customerHeader = request.headers['h-Custom']
|
|
297
|
+
reply.status(200).send({username});
|
|
291
298
|
}
|
|
292
299
|
})
|
|
293
300
|
|
|
@@ -331,6 +338,7 @@ const todo = {
|
|
|
331
338
|
With the provided type `FromSchema` you can build a type from your schema and use it in your handler.
|
|
332
339
|
|
|
333
340
|
```typescript
|
|
341
|
+
import { FromSchema } from "json-schema-to-ts";
|
|
334
342
|
fastify.post<{ Body: FromSchema<typeof todo> }>(
|
|
335
343
|
'/todo',
|
|
336
344
|
{
|
|
@@ -253,7 +253,7 @@ curl -X GET "http://localhost:3000/?ids=1
|
|
|
253
253
|
{"params":{"hello":["1"]}}
|
|
254
254
|
```
|
|
255
255
|
|
|
256
|
-
For further information see [here](https://ajv.js.org/
|
|
256
|
+
For further information see [here](https://ajv.js.org/coercion.html)
|
|
257
257
|
|
|
258
258
|
<a name="ajv-plugins"></a>
|
|
259
259
|
#### Ajv Plugins
|
package/fastify.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import * as http from 'http'
|
|
2
2
|
import * as http2 from 'http2'
|
|
3
3
|
import * as https from 'https'
|
|
4
|
-
import * as LightMyRequest from 'light-my-request'
|
|
5
4
|
import { ConstraintStrategy, HTTPVersion } from 'find-my-way'
|
|
6
5
|
|
|
7
6
|
import { FastifyRequest, RequestGenericInterface } from './types/request'
|
|
@@ -55,7 +54,8 @@ export type FastifyHttp2SecureOptions<
|
|
|
55
54
|
Logger extends FastifyLoggerInstance = FastifyLoggerInstance
|
|
56
55
|
> = FastifyServerOptions<Server, Logger> & {
|
|
57
56
|
http2: true,
|
|
58
|
-
https: http2.SecureServerOptions
|
|
57
|
+
https: http2.SecureServerOptions,
|
|
58
|
+
http2SessionTimeout?: number
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
export type FastifyHttp2Options<
|
|
@@ -63,7 +63,7 @@ export type FastifyHttp2Options<
|
|
|
63
63
|
Logger extends FastifyLoggerInstance = FastifyLoggerInstance
|
|
64
64
|
> = FastifyServerOptions<Server, Logger> & {
|
|
65
65
|
http2: true,
|
|
66
|
-
http2SessionTimeout?: number
|
|
66
|
+
http2SessionTimeout?: number
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
export type FastifyHttpsOptions<
|
|
@@ -159,6 +159,7 @@ export interface ValidationResult {
|
|
|
159
159
|
}
|
|
160
160
|
|
|
161
161
|
/* Export all additional types */
|
|
162
|
+
export type { Chain as LightMyRequestChain, InjectOptions, Response as LightMyRequestResponse, CallbackFunc as LightMyRequestCallback } from 'light-my-request'
|
|
162
163
|
export { FastifyRequest, RequestGenericInterface } from './types/request'
|
|
163
164
|
export { FastifyReply } from './types/reply'
|
|
164
165
|
export { FastifyPluginCallback, FastifyPluginAsync, FastifyPluginOptions, FastifyPlugin } from './types/plugin'
|
package/fastify.js
CHANGED
|
@@ -4,9 +4,8 @@ const Avvio = require('avvio')
|
|
|
4
4
|
const http = require('http')
|
|
5
5
|
const querystring = require('querystring')
|
|
6
6
|
let lightMyRequest
|
|
7
|
-
let version
|
|
8
|
-
let versionLoaded = false
|
|
9
7
|
|
|
8
|
+
const { version } = require('./package.json')
|
|
10
9
|
const {
|
|
11
10
|
kAvvioBoot,
|
|
12
11
|
kChildren,
|
|
@@ -35,7 +34,7 @@ const supportedMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTI
|
|
|
35
34
|
const decorator = require('./lib/decorate')
|
|
36
35
|
const ContentTypeParser = require('./lib/contentTypeParser')
|
|
37
36
|
const SchemaController = require('./lib/schema-controller')
|
|
38
|
-
const { Hooks, hookRunnerApplication } = require('./lib/hooks')
|
|
37
|
+
const { Hooks, hookRunnerApplication, supportedHooks } = require('./lib/hooks')
|
|
39
38
|
const { createLogger } = require('./lib/logger')
|
|
40
39
|
const pluginUtils = require('./lib/pluginUtils')
|
|
41
40
|
const reqIdGenFactory = require('./lib/reqIdGenFactory')
|
|
@@ -58,6 +57,19 @@ const onBadUrlContext = {
|
|
|
58
57
|
onError: []
|
|
59
58
|
}
|
|
60
59
|
|
|
60
|
+
function defaultBuildPrettyMeta (route) {
|
|
61
|
+
// return a shallow copy of route's sanitized context
|
|
62
|
+
|
|
63
|
+
const cleanKeys = {}
|
|
64
|
+
const allowedProps = ['errorHandler', 'logLevel', 'logSerializers']
|
|
65
|
+
|
|
66
|
+
allowedProps.concat(supportedHooks).forEach(k => {
|
|
67
|
+
cleanKeys[k] = route.store[k]
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
return Object.assign({}, cleanKeys)
|
|
71
|
+
}
|
|
72
|
+
|
|
61
73
|
function defaultErrorHandler (error, request, reply) {
|
|
62
74
|
if (reply.statusCode < 500) {
|
|
63
75
|
reply.log.info(
|
|
@@ -158,7 +170,8 @@ function fastify (options) {
|
|
|
158
170
|
constraints: constraints,
|
|
159
171
|
ignoreTrailingSlash: options.ignoreTrailingSlash || defaultInitOptions.ignoreTrailingSlash,
|
|
160
172
|
maxParamLength: options.maxParamLength || defaultInitOptions.maxParamLength,
|
|
161
|
-
caseSensitive: options.caseSensitive
|
|
173
|
+
caseSensitive: options.caseSensitive,
|
|
174
|
+
buildPrettyMeta: defaultBuildPrettyMeta
|
|
162
175
|
}
|
|
163
176
|
})
|
|
164
177
|
|
|
@@ -278,7 +291,7 @@ function fastify (options) {
|
|
|
278
291
|
// fake http injection
|
|
279
292
|
inject: inject,
|
|
280
293
|
// pretty print of the registered routes
|
|
281
|
-
printRoutes
|
|
294
|
+
printRoutes,
|
|
282
295
|
// custom error handling
|
|
283
296
|
setNotFoundHandler: setNotFoundHandler,
|
|
284
297
|
setErrorHandler: setErrorHandler,
|
|
@@ -309,9 +322,6 @@ function fastify (options) {
|
|
|
309
322
|
},
|
|
310
323
|
version: {
|
|
311
324
|
get () {
|
|
312
|
-
if (versionLoaded === false) {
|
|
313
|
-
version = loadVersion()
|
|
314
|
-
}
|
|
315
325
|
return version
|
|
316
326
|
}
|
|
317
327
|
},
|
|
@@ -626,6 +636,12 @@ function fastify (options) {
|
|
|
626
636
|
this[kErrorHandler] = func.bind(this)
|
|
627
637
|
return this
|
|
628
638
|
}
|
|
639
|
+
|
|
640
|
+
function printRoutes (opts = {}) {
|
|
641
|
+
// includeHooks:true - shortcut to include all supported hooks exported by fastify.Hooks
|
|
642
|
+
opts.includeMeta = opts.includeHooks ? opts.includeMeta ? supportedHooks.concat(opts.includeMeta) : supportedHooks : opts.includeMeta
|
|
643
|
+
return router.printRoutes(opts)
|
|
644
|
+
}
|
|
629
645
|
}
|
|
630
646
|
|
|
631
647
|
function validateSchemaErrorFormatter (schemaErrorFormatter) {
|
|
@@ -655,20 +671,6 @@ function wrapRouting (httpHandler, { rewriteUrl, logger }) {
|
|
|
655
671
|
}
|
|
656
672
|
}
|
|
657
673
|
|
|
658
|
-
function loadVersion () {
|
|
659
|
-
versionLoaded = true
|
|
660
|
-
const fs = require('fs')
|
|
661
|
-
const path = require('path')
|
|
662
|
-
try {
|
|
663
|
-
const pkgPath = path.join(__dirname, 'package.json')
|
|
664
|
-
fs.accessSync(pkgPath, fs.constants.R_OK)
|
|
665
|
-
const pkg = JSON.parse(fs.readFileSync(pkgPath))
|
|
666
|
-
return pkg.name === 'fastify' ? pkg.version : undefined
|
|
667
|
-
} catch (e) {
|
|
668
|
-
return undefined
|
|
669
|
-
}
|
|
670
|
-
}
|
|
671
|
-
|
|
672
674
|
/**
|
|
673
675
|
* These export configurations enable JS and TS developers
|
|
674
676
|
* to consumer fastify in whatever way best suits their needs.
|