fastify 4.5.3 → 4.7.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/docs/Guides/Ecosystem.md +42 -16
- package/docs/Guides/Migration-Guide-V4.md +97 -48
- package/docs/Guides/Plugins-Guide.md +44 -0
- package/docs/Guides/Write-Plugin.md +1 -1
- package/docs/Reference/Logging.md +16 -13
- package/docs/Reference/Reply.md +5 -5
- package/docs/Reference/Request.md +19 -6
- package/docs/Reference/Routes.md +2 -2
- package/docs/Reference/Server.md +24 -2
- package/docs/Reference/Type-Providers.md +5 -19
- package/docs/Reference/TypeScript.md +7 -14
- package/examples/typescript-server.ts +1 -1
- package/fastify.d.ts +2 -2
- package/fastify.js +4 -1
- package/lib/contentTypeParser.js +10 -9
- package/lib/context.js +27 -3
- package/lib/error-handler.js +7 -3
- package/lib/error-serializer.js +13 -40
- package/lib/handleRequest.js +15 -13
- package/lib/reply.js +42 -34
- package/lib/request.js +36 -18
- package/lib/route.js +25 -10
- package/lib/schema-controller.js +7 -1
- package/lib/schemas.js +1 -0
- package/lib/server.js +6 -1
- package/lib/symbols.js +2 -0
- package/lib/validation.js +4 -3
- package/lib/warnings.js +2 -0
- package/package.json +26 -26
- package/test/404s.test.js +19 -1
- package/test/context-config.test.js +2 -1
- package/test/handler-context.test.js +12 -30
- package/test/has-route.test.js +77 -0
- package/test/internals/contentTypeParser.test.js +3 -3
- package/test/internals/handleRequest.test.js +4 -3
- package/test/internals/reply-serialize.test.js +9 -9
- package/test/internals/reply.test.js +10 -9
- package/test/internals/request-validate.test.js +97 -9
- package/test/internals/request.test.js +57 -3
- package/test/internals/validation.test.js +15 -0
- package/test/listen.deprecated.test.js +33 -0
- package/test/plugin.test.js +1 -1
- package/test/reply-code.test.js +59 -0
- package/test/route.test.js +29 -0
- package/test/router-options.test.js +33 -66
- package/test/schema-feature.test.js +25 -0
- package/test/schema-special-usage.test.js +29 -0
- package/test/schema-validation.test.js +19 -0
- package/test/search.test.js +169 -30
- package/test/server.test.js +54 -0
- package/test/types/fastify.test-d.ts +9 -0
- package/test/types/route.test-d.ts +11 -0
- package/test/unsupported-httpversion.test.js +0 -26
- package/types/hooks.d.ts +25 -25
- package/types/instance.d.ts +27 -21
- package/types/logger.d.ts +1 -1
- package/types/plugin.d.ts +3 -3
- package/types/reply.d.ts +2 -2
- package/types/request.d.ts +11 -5
- package/types/route.d.ts +9 -9
package/docs/Guides/Ecosystem.md
CHANGED
|
@@ -75,13 +75,23 @@ section.
|
|
|
75
75
|
connection pool across every part of your server.
|
|
76
76
|
- [`@fastify/multipart`](https://github.com/fastify/fastify-multipart) Multipart
|
|
77
77
|
support for Fastify.
|
|
78
|
+
- [`@fastify/nextjs`](https://github.com/fastify/fastify-nextjs) React
|
|
79
|
+
server-side rendering support for Fastify with
|
|
80
|
+
[Next](https://github.com/zeit/next.js/).
|
|
78
81
|
- [`@fastify/oauth2`](https://github.com/fastify/fastify-oauth2) Wrap around
|
|
79
82
|
[`simple-oauth2`](https://github.com/lelylan/simple-oauth2).
|
|
83
|
+
- [`@fastify/one-line-logger`](https://github.com/fastify/one-line-logger) Formats
|
|
84
|
+
Fastify's logs into a nice one-line message.
|
|
80
85
|
- [`@fastify/postgres`](https://github.com/fastify/fastify-postgres) Fastify
|
|
81
86
|
PostgreSQL connection plugin, with this you can share the same PostgreSQL
|
|
82
87
|
connection pool in every part of your server.
|
|
83
88
|
- [`@fastify/rate-limit`](https://github.com/fastify/fastify-rate-limit) A low
|
|
84
89
|
overhead rate limiter for your routes.
|
|
90
|
+
- [`@fastify/redis`](https://github.com/fastify/fastify-redis) Fastify Redis
|
|
91
|
+
connection plugin, with which you can share the same Redis connection across
|
|
92
|
+
every part of your server.
|
|
93
|
+
- [`@fastify/reply-from`](https://github.com/fastify/fastify-reply-from) Plugin
|
|
94
|
+
to forward the current HTTP request to another server.
|
|
85
95
|
- [`@fastify/request-context`](https://github.com/fastify/fastify-request-context)
|
|
86
96
|
Request-scoped storage, based on
|
|
87
97
|
[AsyncLocalStorage](https://nodejs.org/api/async_hooks.html#async_hooks_class_asynclocalstorage)
|
|
@@ -89,14 +99,6 @@ section.
|
|
|
89
99
|
providing functionality similar to thread-local storages.
|
|
90
100
|
- [`@fastify/response-validation`](https://github.com/fastify/fastify-response-validation)
|
|
91
101
|
A simple plugin that enables response validation for Fastify.
|
|
92
|
-
- [`@fastify/nextjs`](https://github.com/fastify/fastify-nextjs) React
|
|
93
|
-
server-side rendering support for Fastify with
|
|
94
|
-
[Next](https://github.com/zeit/next.js/).
|
|
95
|
-
- [`@fastify/redis`](https://github.com/fastify/fastify-redis) Fastify Redis
|
|
96
|
-
connection plugin, with which you can share the same Redis connection across
|
|
97
|
-
every part of your server.
|
|
98
|
-
- [`@fastify/reply-from`](https://github.com/fastify/fastify-reply-from) Plugin
|
|
99
|
-
to forward the current HTTP request to another server.
|
|
100
102
|
- [`@fastify/routes`](https://github.com/fastify/fastify-routes) Plugin that
|
|
101
103
|
provides a `Map` of routes.
|
|
102
104
|
- [`@fastify/schedule`](https://github.com/fastify/fastify-schedule) Plugin for
|
|
@@ -119,10 +121,10 @@ section.
|
|
|
119
121
|
- [`@fastify/type-provider-json-schema-to-ts`](https://github.com/fastify/fastify-type-provider-json-schema-to-ts)
|
|
120
122
|
Fastify
|
|
121
123
|
[type provider](https://www.fastify.io/docs/latest/Reference/Type-Providers/)
|
|
122
|
-
for [json-schema-to-ts](https://github.com/ThomasAribart/json-schema-to-ts).
|
|
124
|
+
for [json-schema-to-ts](https://github.com/ThomasAribart/json-schema-to-ts).
|
|
123
125
|
- [`@fastify/type-provider-typebox`](https://github.com/fastify/fastify-type-provider-typebox)
|
|
124
126
|
Fastify
|
|
125
|
-
[type provider](https://www.fastify.io/docs/latest/Reference/Type-Providers/)
|
|
127
|
+
[type provider](https://www.fastify.io/docs/latest/Reference/Type-Providers/)
|
|
126
128
|
for [Typebox](https://github.com/sinclairzx81/typebox).
|
|
127
129
|
- [`@fastify/under-pressure`](https://github.com/fastify/under-pressure) Measure
|
|
128
130
|
process load with automatic handling of _"Service Unavailable"_ plugin for
|
|
@@ -146,6 +148,13 @@ section.
|
|
|
146
148
|
close the server gracefully on `SIGINT` and `SIGTERM` signals.
|
|
147
149
|
- [`@eropple/fastify-openapi3`](https://github.com/eropple/fastify-openapi3) Provides
|
|
148
150
|
easy, developer-friendly OpenAPI 3.1 specs + doc explorer based on your routes.
|
|
151
|
+
- [`@ethicdevs/fastify-custom-session`](https://github.com/EthicDevs/fastify-custom-session)
|
|
152
|
+
A plugin that let you use session and decide only where to load/save from/to. Has
|
|
153
|
+
great TypeScript support + built-in adapters for common ORMs/databases (Firebase,
|
|
154
|
+
Prisma Client, Postgres (wip), InMemory) and you can easily make your own adapter!
|
|
155
|
+
- [`@ethicdevs/fastify-git-server`](https://github.com/EthicDevs/fastify-git-server)
|
|
156
|
+
A plugin to easily create git server and make one/many Git repositories available
|
|
157
|
+
for clone/fetch/push through the standard `git` (over http) commands.
|
|
149
158
|
- [`@gquittet/graceful-server`](https://github.com/gquittet/graceful-server)
|
|
150
159
|
Tiny (~5k), Fast, KISS, and dependency-free Node.JS library to make your
|
|
151
160
|
Fastify API graceful.
|
|
@@ -160,7 +169,7 @@ section.
|
|
|
160
169
|
Sentry errors handler that just works! Install, add your DSN and you're good
|
|
161
170
|
to go!
|
|
162
171
|
- [`@mateonunez/fastify-lyra`](https://github.com/mateonunez/fastify-lyra)
|
|
163
|
-
A plugin to implement [Lyra](https://github.com/nearform/lyra) search engine
|
|
172
|
+
A plugin to implement [Lyra](https://github.com/nearform/lyra) search engine
|
|
164
173
|
on Fastify
|
|
165
174
|
- [`@mgcrea/fastify-graceful-exit`](https://github.com/mgcrea/fastify-graceful-exit)
|
|
166
175
|
A plugin to close the server gracefully
|
|
@@ -184,7 +193,7 @@ section.
|
|
|
184
193
|
- [`cls-rtracer`](https://github.com/puzpuzpuz/cls-rtracer) Fastify middleware
|
|
185
194
|
for CLS-based request ID generation. An out-of-the-box solution for adding
|
|
186
195
|
request IDs into your logs.
|
|
187
|
-
- [`electron-server`](https://github.com/anonrig/electron-server) A plugin for
|
|
196
|
+
- [`electron-server`](https://github.com/anonrig/electron-server) A plugin for
|
|
188
197
|
using Fastify without the need of consuming a port on Electron apps.
|
|
189
198
|
- [`fast-water`](https://github.com/tswayne/fast-water) A Fastify plugin for
|
|
190
199
|
waterline. Decorates Fastify with waterline models.
|
|
@@ -216,6 +225,12 @@ section.
|
|
|
216
225
|
- [`fastify-autoroutes`](https://github.com/GiovanniCardamone/fastify-autoroutes)
|
|
217
226
|
Plugin to scan and load routes based on filesystem path from a custom
|
|
218
227
|
directory.
|
|
228
|
+
- [`fastify-aws-sns`](https://github.com/gzileni/fastify-aws-sns) Fastify plugin
|
|
229
|
+
for AWS Simple Notification Service (AWS SNS) that coordinates and manages
|
|
230
|
+
the delivery or sending of messages to subscribing endpoints or clients.
|
|
231
|
+
- [`fastify-aws-timestream`](https://github.com/gzileni/fastify-aws-timestream)
|
|
232
|
+
Fastify plugin for managing databases, tables, and querying and creating
|
|
233
|
+
scheduled queries with AWS Timestream.
|
|
219
234
|
- [`fastify-axios`](https://github.com/davidedantonio/fastify-axios) Plugin to
|
|
220
235
|
send HTTP requests via [axios](https://github.com/axios/axios).
|
|
221
236
|
- [`fastify-babel`](https://github.com/cfware/fastify-babel) Fastify plugin for
|
|
@@ -433,7 +448,7 @@ section.
|
|
|
433
448
|
OrientDB connection plugin, with which you can share the OrientDB connection
|
|
434
449
|
across every part of your server.
|
|
435
450
|
- [`fastify-osm`](https://github.com/gzileni/fastify-osm) Fastify
|
|
436
|
-
OSM plugin to run overpass queries by OpenStreetMap.
|
|
451
|
+
OSM plugin to run overpass queries by OpenStreetMap.
|
|
437
452
|
- [`fastify-peekaboo`](https://github.com/simone-sanfratello/fastify-peekaboo)
|
|
438
453
|
Fastify plugin for memoize responses by expressive settings.
|
|
439
454
|
- [`fastify-piscina`](https://github.com/piscinajs/fastify-piscina) A worker
|
|
@@ -458,6 +473,9 @@ section.
|
|
|
458
473
|
[qs](https://github.com/ljharb/qs).
|
|
459
474
|
- [`fastify-racing`](https://github.com/metcoder95/fastify-racing) Fastify's
|
|
460
475
|
plugin that adds support to handle an aborted request asynchronous.
|
|
476
|
+
- [`fastify-ravendb`](https://github.com/nearform/fastify-ravendb) RavenDB
|
|
477
|
+
connection plugin. It exposes the same `DocumentStore` (or multiple ones)
|
|
478
|
+
across the whole Fastify application.
|
|
461
479
|
- [`fastify-raw-body`](https://github.com/Eomm/fastify-raw-body) Add the
|
|
462
480
|
`request.rawBody` field.
|
|
463
481
|
- [`fastify-rbac`](https://gitlab.com/m03geek/fastify-rbac) Fastify role-based
|
|
@@ -483,7 +501,9 @@ section.
|
|
|
483
501
|
- [`fastify-rob-config`](https://github.com/jeromemacias/fastify-rob-config)
|
|
484
502
|
Fastify Rob-Config integration.
|
|
485
503
|
- [`fastify-route-group`](https://github.com/TakNePoidet/fastify-route-group)
|
|
486
|
-
Convenient grouping and inheritance of routes
|
|
504
|
+
Convenient grouping and inheritance of routes.
|
|
505
|
+
- [`fastify-s3-buckets`](https://github.com/kibertoad/fastify-s3-buckets)
|
|
506
|
+
Ensure the existence of defined S3 buckets on the application startup.
|
|
487
507
|
- [`fastify-schema-constraint`](https://github.com/Eomm/fastify-schema-constraint)
|
|
488
508
|
Choose the JSON schema to use based on request parameters.
|
|
489
509
|
- [`fastify-schema-to-typescript`](https://github.com/thomasthiebaud/fastify-schema-to-typescript)
|
|
@@ -499,11 +519,15 @@ section.
|
|
|
499
519
|
`fastify-caching`.
|
|
500
520
|
- [`fastify-slonik`](https://github.com/Unbuttun/fastify-slonik) Fastify Slonik
|
|
501
521
|
plugin, with this you can use slonik in every part of your server.
|
|
522
|
+
- [`fastify-slow-down`](https://github.com/nearform/fastify-slow-down) A plugin
|
|
523
|
+
to delay the response from the server.
|
|
502
524
|
- [`fastify-socket.io`](https://github.com/alemagio/fastify-socket.io) a
|
|
503
525
|
Socket.io plugin for Fastify.
|
|
504
526
|
- [`fastify-split-validator`](https://github.com/MetCoder95/fastify-split-validator)
|
|
505
527
|
Small plugin to allow you use multiple validators in one route based on each
|
|
506
528
|
HTTP part of the request.
|
|
529
|
+
- [`fastify-sqlite`](https://github.com/Eomm/fastify-sqlite) connects your
|
|
530
|
+
application to a sqlite3 database.
|
|
507
531
|
- [`fastify-sse`](https://github.com/lolo32/fastify-sse) to provide Server-Sent
|
|
508
532
|
Events with `reply.sse( … )` to Fastify.
|
|
509
533
|
- [`fastify-sse-v2`](https://github.com/nodefactoryio/fastify-sse-v2) to provide
|
|
@@ -528,8 +552,8 @@ section.
|
|
|
528
552
|
- [`fastify-twitch-ebs-tools`](https://github.com/lukemnet/fastify-twitch-ebs-tools)
|
|
529
553
|
Useful functions for Twitch Extension Backend Services (EBS).
|
|
530
554
|
- [`fastify-type-provider-zod`](https://github.com/turkerdev/fastify-type-provider-zod)
|
|
531
|
-
Fastify
|
|
532
|
-
[type provider](https://www.fastify.io/docs/latest/Reference/Type-Providers/)
|
|
555
|
+
Fastify
|
|
556
|
+
[type provider](https://www.fastify.io/docs/latest/Reference/Type-Providers/)
|
|
533
557
|
for [zod](https://github.com/colinhacks/zod).
|
|
534
558
|
- [`fastify-typeorm-plugin`](https://github.com/inthepocket/fastify-typeorm-plugin)
|
|
535
559
|
Fastify plugin to work with TypeORM.
|
|
@@ -574,6 +598,8 @@ section.
|
|
|
574
598
|
- [`openapi-validator-middleware`](https://github.com/PayU/openapi-validator-middleware#fastify)
|
|
575
599
|
Swagger and OpenAPI 3.0 spec-based request validation middleware that supports
|
|
576
600
|
Fastify.
|
|
601
|
+
- [`pubsub-http-handler`](https://github.com/cobraz/pubsub-http-handler) A Fastify
|
|
602
|
+
plugin to easily create Google Cloud PubSub endpoints.
|
|
577
603
|
- [`sequelize-fastify`](https://github.com/hsynlms/sequelize-fastify) A simple
|
|
578
604
|
and lightweight Sequelize plugin for Fastify.
|
|
579
605
|
- [`typeorm-fastify-plugin`](https://github.com/jclemens24/fastify-typeorm) A simple
|
|
@@ -10,12 +10,11 @@ work after upgrading.
|
|
|
10
10
|
|
|
11
11
|
### Error handling composition ([#3261](https://github.com/fastify/fastify/pull/3261))
|
|
12
12
|
|
|
13
|
-
When an error is thrown in
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
be executed as it was previously.
|
|
13
|
+
When an error is thrown in an async error handler function, the upper-level
|
|
14
|
+
error handler is executed if set. If there is no upper-level error handler,
|
|
15
|
+
the default will be executed as it was previously:
|
|
17
16
|
|
|
18
|
-
```
|
|
17
|
+
```js
|
|
19
18
|
import Fastify from 'fastify'
|
|
20
19
|
|
|
21
20
|
const fastify = Fastify()
|
|
@@ -40,75 +39,125 @@ const res = await fastify.inject('/encapsulated')
|
|
|
40
39
|
console.log(res.json().message) // 'wrapped'
|
|
41
40
|
```
|
|
42
41
|
|
|
43
|
-
###
|
|
42
|
+
### Removed `app.use()` ([#3506](https://github.com/fastify/fastify/pull/3506))
|
|
43
|
+
|
|
44
|
+
With v4 of Fastify, `app.use()` has been removed and the use of middleware is
|
|
45
|
+
no longer supported.
|
|
44
46
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
[`@fastify/
|
|
48
|
-
|
|
49
|
-
|
|
47
|
+
If you need to use middleware, use
|
|
48
|
+
[`@fastify/middie`](https://github.com/fastify/middie) or
|
|
49
|
+
[`@fastify/express`](https://github.com/fastify/fastify-express), which will
|
|
50
|
+
continue to be maintained.
|
|
51
|
+
However, it is strongly recommended that you migrate to Fastify's [hooks](../Reference/Hooks.md).
|
|
50
52
|
|
|
51
53
|
### `reply.res` moved to `reply.raw`
|
|
52
54
|
|
|
53
55
|
If you previously used the `reply.res` attribute to access the underlying Request
|
|
54
|
-
object you
|
|
56
|
+
object you will now need to use `reply.raw`.
|
|
55
57
|
|
|
56
58
|
### Need to `return reply` to signal a "fork" of the promise chain
|
|
57
59
|
|
|
58
|
-
In some situations, like when a response is sent asynchronously or when you
|
|
59
|
-
|
|
60
|
+
In some situations, like when a response is sent asynchronously or when you are
|
|
61
|
+
not explicitly returning a response, you will now need to return the `reply`
|
|
60
62
|
argument from your router handler.
|
|
61
63
|
|
|
62
64
|
### `exposeHeadRoutes` true by default
|
|
63
65
|
|
|
64
|
-
Starting
|
|
65
|
-
You can revert this
|
|
66
|
-
to `false`.
|
|
66
|
+
Starting with v4, every `GET` route will create a sibling `HEAD` route.
|
|
67
|
+
You can revert this behavior by setting `exposeHeadRoutes: false` in the server options.
|
|
67
68
|
|
|
68
|
-
### Synchronous route definitions
|
|
69
|
+
### Synchronous route definitions ([#2954](https://github.com/fastify/fastify/pull/2954))
|
|
69
70
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
As a result if you specify an `onRoute` hook in a plugin you should either:
|
|
71
|
+
To improve error reporting in route definitions, route registration is now synchronous.
|
|
72
|
+
As a result, if you specify an `onRoute` hook in a plugin you should now either:
|
|
73
73
|
* wrap your routes in a plugin (recommended)
|
|
74
|
+
|
|
75
|
+
For example, refactor this:
|
|
76
|
+
```js
|
|
77
|
+
fastify.register((instance, opts, done) => {
|
|
78
|
+
instance.addHook('onRoute', (routeOptions) => {
|
|
79
|
+
const { path, method } = routeOptions;
|
|
80
|
+
console.log({ path, method });
|
|
81
|
+
done();
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
fastify.get('/', (request, reply) => { reply.send('hello') });
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Into this:
|
|
89
|
+
```js
|
|
90
|
+
fastify.register((instance, opts, done) => {
|
|
91
|
+
instance.addHook('onRoute', (routeOptions) => {
|
|
92
|
+
const { path, method } = routeOptions;
|
|
93
|
+
console.log({ path, method });
|
|
94
|
+
done();
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
fastify.register((instance, opts, done) => {
|
|
99
|
+
instance.get('/', (request, reply) => { reply.send('hello') });
|
|
100
|
+
done();
|
|
101
|
+
});
|
|
102
|
+
```
|
|
103
|
+
|
|
74
104
|
* use `await register(...)`
|
|
75
105
|
|
|
76
|
-
For example refactor this:
|
|
77
|
-
```
|
|
78
|
-
fastify.register((instance, opts, done) => {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
106
|
+
For example, refactor this:
|
|
107
|
+
```js
|
|
108
|
+
fastify.register((instance, opts, done) => {
|
|
109
|
+
instance.addHook('onRoute', (routeOptions) => {
|
|
110
|
+
const { path, method } = routeOptions;
|
|
111
|
+
console.log({ path, method });
|
|
112
|
+
});
|
|
113
|
+
done();
|
|
82
114
|
});
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Into this:
|
|
118
|
+
```js
|
|
119
|
+
await fastify.register((instance, opts) => {
|
|
120
|
+
instance.addHook('onRoute', (routeOptions) => {
|
|
121
|
+
const { path, method } = routeOptions;
|
|
122
|
+
console.log({ path, method });
|
|
123
|
+
});
|
|
124
|
+
done();
|
|
92
125
|
});
|
|
93
|
-
|
|
94
|
-
});
|
|
95
|
-
```
|
|
126
|
+
```
|
|
96
127
|
|
|
97
|
-
## Non
|
|
128
|
+
## Non-Breaking Changes
|
|
98
129
|
|
|
99
|
-
###
|
|
130
|
+
### Deprecation of variadic `.listen()` signature
|
|
100
131
|
|
|
132
|
+
The [variadic signature](https://en.wikipedia.org/wiki/Variadic_function) of the
|
|
133
|
+
`fastify.listen()` method is now deprecated.
|
|
101
134
|
|
|
102
|
-
|
|
103
|
-
(other than with "null") are prohibited. Read more
|
|
104
|
-
['here'](https://ajv.js.org/strict-mode.html#strict-types)
|
|
135
|
+
Prior to this release, the following invocations of this method were valid:
|
|
105
136
|
|
|
106
|
-
|
|
137
|
+
- `fastify.listen(8000)`
|
|
138
|
+
- `fastify.listen(8000, ‘127.0.0.1’)`
|
|
139
|
+
- `fastify.listen(8000, ‘127.0.0.1’, 511)`
|
|
140
|
+
- `fastify.listen(8000, (err) => { if (err) throw err })`
|
|
141
|
+
- `fastify.listen({ port: 8000 }, (err) => { if (err) throw err })`
|
|
107
142
|
|
|
108
|
-
|
|
143
|
+
With Fastify v4, only the following invocations are valid:
|
|
144
|
+
|
|
145
|
+
- `fastify.listen()`
|
|
146
|
+
- `fastify.listen({ port: 8000 })`
|
|
147
|
+
- `fastify.listen({ port: 8000 }, (err) => { if (err) throw err })`
|
|
148
|
+
|
|
149
|
+
### Change of schema for multiple types
|
|
150
|
+
|
|
151
|
+
Ajv has been upgraded to v8 in Fastify v4, meaning "type" keywords with multiple
|
|
152
|
+
types other than "null"
|
|
153
|
+
[are now prohibited](https://ajv.js.org/strict-mode.html#strict-types).
|
|
154
|
+
|
|
155
|
+
You may encounter a console warning such as:
|
|
156
|
+
```sh
|
|
109
157
|
strict mode: use allowUnionTypes to allow union type keyword at "#/properties/image" (strictTypes)
|
|
110
158
|
```
|
|
111
|
-
|
|
159
|
+
|
|
160
|
+
As such, schemas like below will need to be changed from:
|
|
112
161
|
```
|
|
113
162
|
type: 'object',
|
|
114
163
|
properties: {
|
|
@@ -117,8 +166,8 @@ properties: {
|
|
|
117
166
|
}
|
|
118
167
|
}
|
|
119
168
|
```
|
|
120
|
-
to
|
|
121
169
|
|
|
170
|
+
Into:
|
|
122
171
|
```
|
|
123
172
|
type: 'object',
|
|
124
173
|
properties: {
|
|
@@ -308,6 +308,50 @@ fastify.get('/plugin2', (request, reply) => {
|
|
|
308
308
|
```
|
|
309
309
|
Now your hook will run just for the first route!
|
|
310
310
|
|
|
311
|
+
An alternative approach is to make use of the [onRoute hook](../Reference/Hooks.md#onroute)
|
|
312
|
+
to customize application routes dynamically from inside the plugin. Every time
|
|
313
|
+
a new route is registered, you can read and modify the route options. For example,
|
|
314
|
+
based on a [route config option](../Reference/Routes.md#routes-options):
|
|
315
|
+
|
|
316
|
+
```js
|
|
317
|
+
fastify.register((instance, opts, done) => {
|
|
318
|
+
instance.decorate('util', (request, key, value) => { request[key] = value })
|
|
319
|
+
|
|
320
|
+
function handler(request, reply, done) {
|
|
321
|
+
instance.util(request, 'timestamp', new Date())
|
|
322
|
+
done()
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
instance.addHook('onRoute', (routeOptions) => {
|
|
326
|
+
if (routeOptions.config && routeOptions.config.useUtil === true) {
|
|
327
|
+
// set or add our handler to the route preHandler hook
|
|
328
|
+
if (!routeOptions.preHandler) {
|
|
329
|
+
routeOptions.preHandler = [handler]
|
|
330
|
+
return
|
|
331
|
+
}
|
|
332
|
+
if (Array.isArray(routeOptions.preHandler)) {
|
|
333
|
+
routeOptions.preHandler.push(handler)
|
|
334
|
+
return
|
|
335
|
+
}
|
|
336
|
+
routeOptions.preHandler = [routeOptions.preHandler, handler]
|
|
337
|
+
}
|
|
338
|
+
})
|
|
339
|
+
|
|
340
|
+
fastify.get('/plugin1', {config: {useUtil: true}}, (request, reply) => {
|
|
341
|
+
reply.send(request)
|
|
342
|
+
})
|
|
343
|
+
|
|
344
|
+
fastify.get('/plugin2', (request, reply) => {
|
|
345
|
+
reply.send(request)
|
|
346
|
+
})
|
|
347
|
+
|
|
348
|
+
done()
|
|
349
|
+
})
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
This variant becomes extremely useful if you plan to distribute your plugin, as
|
|
353
|
+
described in the next section.
|
|
354
|
+
|
|
311
355
|
As you probably noticed by now, `request` and `reply` are not the standard
|
|
312
356
|
Nodejs *request* and *response* objects, but Fastify's objects.
|
|
313
357
|
|
|
@@ -80,7 +80,7 @@ to show that the plugin works as intended. Both
|
|
|
80
80
|
Actions](https://github.com/features/actions) are free for open source projects
|
|
81
81
|
and easy to set up.
|
|
82
82
|
|
|
83
|
-
In addition, you can enable services like [Dependabot](https://
|
|
83
|
+
In addition, you can enable services like [Dependabot](https://github.com/dependabot),
|
|
84
84
|
which will help you keep your dependencies up to date and discover if a new
|
|
85
85
|
release of Fastify has some issues with your plugin.
|
|
86
86
|
|
|
@@ -22,21 +22,24 @@ const fastify = require('fastify')({
|
|
|
22
22
|
```
|
|
23
23
|
|
|
24
24
|
Enabling the logger with appropriate configuration for both local development
|
|
25
|
-
and production environment requires bit more configuration:
|
|
25
|
+
and production and test environment requires bit more configuration:
|
|
26
|
+
|
|
26
27
|
```js
|
|
28
|
+
const envToLogger = {
|
|
29
|
+
development: {
|
|
30
|
+
transport: {
|
|
31
|
+
target: 'pino-pretty',
|
|
32
|
+
options: {
|
|
33
|
+
translateTime: 'HH:MM:ss Z',
|
|
34
|
+
ignore: 'pid,hostname',
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
},
|
|
38
|
+
production: true,
|
|
39
|
+
test: false,
|
|
40
|
+
}
|
|
27
41
|
const fastify = require('fastify')({
|
|
28
|
-
logger:
|
|
29
|
-
transport:
|
|
30
|
-
environment === 'development'
|
|
31
|
-
? {
|
|
32
|
-
target: 'pino-pretty',
|
|
33
|
-
options: {
|
|
34
|
-
translateTime: 'HH:MM:ss Z',
|
|
35
|
-
ignore: 'pid,hostname'
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
: undefined
|
|
39
|
-
}
|
|
42
|
+
logger: envToLogger[environment] ?? true // defaults to true if no entry matches in the map
|
|
40
43
|
})
|
|
41
44
|
```
|
|
42
45
|
⚠️ `pino-pretty` needs to be installed as a dev dependency, it is not included
|
package/docs/Reference/Reply.md
CHANGED
|
@@ -7,22 +7,22 @@
|
|
|
7
7
|
- [.statusCode](#statuscode)
|
|
8
8
|
- [.server](#server)
|
|
9
9
|
- [.header(key, value)](#headerkey-value)
|
|
10
|
-
- [set-cookie](#set-cookie)
|
|
11
10
|
- [.headers(object)](#headersobject)
|
|
12
11
|
- [.getHeader(key)](#getheaderkey)
|
|
13
12
|
- [.getHeaders()](#getheaders)
|
|
13
|
+
- [set-cookie](#set-cookie)
|
|
14
14
|
- [.removeHeader(key)](#removeheaderkey)
|
|
15
15
|
- [.hasHeader(key)](#hasheaderkey)
|
|
16
16
|
- [.trailer(key, function)](#trailerkey-function)
|
|
17
17
|
- [.hasTrailer(key)](#hastrailerkey)
|
|
18
18
|
- [.removeTrailer(key)](#removetrailerkey)
|
|
19
|
-
- [.redirect([code,] dest)](#redirectcode--dest)
|
|
19
|
+
- [.redirect([code ,] dest)](#redirectcode--dest)
|
|
20
20
|
- [.callNotFound()](#callnotfound)
|
|
21
21
|
- [.getResponseTime()](#getresponsetime)
|
|
22
22
|
- [.type(contentType)](#typecontenttype)
|
|
23
|
-
- [.getSerializationFunction(schema | httpStatus)](#
|
|
24
|
-
- [.compileSerializationSchema(schema, httpStatus)](#
|
|
25
|
-
- [.serializeInput(data, [schema | httpStatus], [httpStatus])](#
|
|
23
|
+
- [.getSerializationFunction(schema | httpStatus)](#getserializationfunctionschema--httpstatus)
|
|
24
|
+
- [.compileSerializationSchema(schema, httpStatus)](#compileserializationschemaschema-httpstatus)
|
|
25
|
+
- [.serializeInput(data, [schema | httpStatus], [httpStatus])](#serializeinputdata-schema--httpstatus-httpstatus)
|
|
26
26
|
- [.serializer(func)](#serializerfunc)
|
|
27
27
|
- [.raw](#raw)
|
|
28
28
|
- [.sent](#sent)
|
|
@@ -35,6 +35,13 @@ Request is a core Fastify object containing the following fields:
|
|
|
35
35
|
- `connection` - Deprecated, use `socket` instead. The underlying connection of
|
|
36
36
|
the incoming request.
|
|
37
37
|
- `socket` - the underlying connection of the incoming request
|
|
38
|
+
- `context` - A Fastify internal object. You should not use it directly or
|
|
39
|
+
modify it. It is useful to access one special key:
|
|
40
|
+
- `context.config` - The route [`config`](./Routes.md#routes-config) object.
|
|
41
|
+
- `routeSchema` - the scheme definition set for the router that is
|
|
42
|
+
handling the request
|
|
43
|
+
- `routeConfig` - The route [`config`](./Routes.md#routes-config)
|
|
44
|
+
object.
|
|
38
45
|
- [.getValidationFunction(schema | httpPart)](#getvalidationfunction) -
|
|
39
46
|
Returns a validation function for the specified schema or http part,
|
|
40
47
|
if any of either are set or cached.
|
|
@@ -48,9 +55,6 @@ Request is a core Fastify object containing the following fields:
|
|
|
48
55
|
schema and returns the serialized payload. If the optional
|
|
49
56
|
`httpPart` is provided, the function will use the serializer
|
|
50
57
|
function given for that HTTP Status Code. Defaults to `null`.
|
|
51
|
-
- `context` - A Fastify internal object. You should not use it directly or
|
|
52
|
-
modify it. It is useful to access one special key:
|
|
53
|
-
- `context.config` - The route [`config`](./Routes.md#routes-config) object.
|
|
54
58
|
|
|
55
59
|
### Headers
|
|
56
60
|
|
|
@@ -98,6 +102,9 @@ it will return a `validation` function that can be used to
|
|
|
98
102
|
validate diverse inputs. It returns `undefined` if no
|
|
99
103
|
serialization function was found using either of the provided inputs.
|
|
100
104
|
|
|
105
|
+
This function has property errors. Errors encountered during the last validation
|
|
106
|
+
are assigned to errors
|
|
107
|
+
|
|
101
108
|
```js
|
|
102
109
|
const validate = request
|
|
103
110
|
.getValidationFunction({
|
|
@@ -108,13 +115,15 @@ const validate = request
|
|
|
108
115
|
}
|
|
109
116
|
}
|
|
110
117
|
})
|
|
111
|
-
validate({ foo: 'bar' }) // true
|
|
118
|
+
console.log(validate({ foo: 'bar' })) // true
|
|
119
|
+
console.log(validate.errors) // null
|
|
112
120
|
|
|
113
121
|
// or
|
|
114
122
|
|
|
115
123
|
const validate = request
|
|
116
124
|
.getValidationFunction('body')
|
|
117
|
-
validate({ foo: 0.5 }) // false
|
|
125
|
+
console.log(validate({ foo: 0.5 })) // false
|
|
126
|
+
console.log(validate.errors) // validation errors
|
|
118
127
|
```
|
|
119
128
|
|
|
120
129
|
See [.compilaValidationSchema(schema, [httpStatus])](#compilevalidationschema)
|
|
@@ -133,6 +142,8 @@ The optional parameter `httpPart`, if provided, is forwarded directly
|
|
|
133
142
|
the `ValidationCompiler`, so it can be used to compile the validation
|
|
134
143
|
function if a custom `ValidationCompiler` is provided for the route.
|
|
135
144
|
|
|
145
|
+
This function has property errors. Errors encountered during the last validation
|
|
146
|
+
are assigned to errors
|
|
136
147
|
|
|
137
148
|
```js
|
|
138
149
|
const validate = request
|
|
@@ -145,6 +156,7 @@ const validate = request
|
|
|
145
156
|
}
|
|
146
157
|
})
|
|
147
158
|
console.log(validate({ foo: 'bar' })) // true
|
|
159
|
+
console.log(validate.errors) // null
|
|
148
160
|
|
|
149
161
|
// or
|
|
150
162
|
|
|
@@ -158,6 +170,7 @@ const validate = request
|
|
|
158
170
|
}
|
|
159
171
|
}, 200)
|
|
160
172
|
console.log(validate({ hello: 'world' })) // false
|
|
173
|
+
console.log(validate.errors) // validation errors
|
|
161
174
|
```
|
|
162
175
|
|
|
163
176
|
Note that you should be careful when using this function, as it will cache
|
|
@@ -247,4 +260,4 @@ request
|
|
|
247
260
|
```
|
|
248
261
|
|
|
249
262
|
See [.compileValidationSchema(schema, [httpStatus])](#compileValidationSchema)
|
|
250
|
-
for more information on how to compile validation schemas.
|
|
263
|
+
for more information on how to compile validation schemas.
|
package/docs/Reference/Routes.md
CHANGED
|
@@ -41,8 +41,8 @@ fastify.route(options)
|
|
|
41
41
|
need to be in [JSON Schema](https://json-schema.org/) format, check
|
|
42
42
|
[here](./Validation-and-Serialization.md) for more info.
|
|
43
43
|
|
|
44
|
-
* `body`: validates the body of the request if it is a POST, PUT,
|
|
45
|
-
method.
|
|
44
|
+
* `body`: validates the body of the request if it is a POST, PUT, PATCH,
|
|
45
|
+
TRACE, or SEARCH method.
|
|
46
46
|
* `querystring` or `query`: validates the querystring. This can be a complete
|
|
47
47
|
JSON Schema object, with the property `type` of `object` and `properties`
|
|
48
48
|
object of parameters, or simply the values of what would be contained in the
|
package/docs/Reference/Server.md
CHANGED
|
@@ -54,6 +54,7 @@ describes the properties available in that options object.
|
|
|
54
54
|
- [setDefaultRoute](#setdefaultroute)
|
|
55
55
|
- [routing](#routing)
|
|
56
56
|
- [route](#route)
|
|
57
|
+
- [hasRoute](#hasRoute)
|
|
57
58
|
- [close](#close)
|
|
58
59
|
- [decorate*](#decorate)
|
|
59
60
|
- [register](#register)
|
|
@@ -667,7 +668,7 @@ the incoming request as usual.
|
|
|
667
668
|
|
|
668
669
|
Configure the Ajv v8 instance used by Fastify without providing a custom one.
|
|
669
670
|
The default configuration is explained in the
|
|
670
|
-
[#schema-validator](Validation-and-Serialization.md#schema-validator) section.
|
|
671
|
+
[#schema-validator](./Validation-and-Serialization.md#schema-validator) section.
|
|
671
672
|
|
|
672
673
|
```js
|
|
673
674
|
const fastify = require('fastify')({
|
|
@@ -1020,7 +1021,8 @@ const defaultRoute = fastify.getDefaultRoute()
|
|
|
1020
1021
|
<a id="setDefaultRoute"></a>
|
|
1021
1022
|
|
|
1022
1023
|
**Note**: The default 404 handler, or one set using `setNotFoundHandler`, will
|
|
1023
|
-
never trigger if the default route is overridden.
|
|
1024
|
+
never trigger if the default route is overridden. This sets the handler for the
|
|
1025
|
+
Fastify application, not just the current instance context. Use
|
|
1024
1026
|
[setNotFoundHandler](#setnotfoundhandler) if you want to customize 404 handling
|
|
1025
1027
|
instead. Method to set the `defaultRoute` for the server:
|
|
1026
1028
|
|
|
@@ -1048,6 +1050,26 @@ fastify.routing(req, res)
|
|
|
1048
1050
|
Method to add routes to the server, it also has shorthand functions, check
|
|
1049
1051
|
[here](./Routes.md).
|
|
1050
1052
|
|
|
1053
|
+
#### hasRoute
|
|
1054
|
+
<a id="hasRoute"></a>
|
|
1055
|
+
|
|
1056
|
+
Method to check if a route is already registered to the internal router. It
|
|
1057
|
+
expects an object as payload. `url` and `method` are mandatory fields. It is
|
|
1058
|
+
possible to also specify `constraints`. The method returns true if the route is
|
|
1059
|
+
registered, and false if it is not registered.
|
|
1060
|
+
|
|
1061
|
+
```js
|
|
1062
|
+
const routeExists = fastify.hasRoute({
|
|
1063
|
+
url: '/',
|
|
1064
|
+
method: 'GET',
|
|
1065
|
+
constraints: { version: '1.0.0' } // optional
|
|
1066
|
+
})
|
|
1067
|
+
|
|
1068
|
+
if (routeExists === false) {
|
|
1069
|
+
// add route
|
|
1070
|
+
}
|
|
1071
|
+
```
|
|
1072
|
+
|
|
1051
1073
|
#### close
|
|
1052
1074
|
<a id="close"></a>
|
|
1053
1075
|
|