fastify 4.2.1 → 4.5.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/build/build-validation.js +1 -1
- package/docs/Guides/Ecosystem.md +25 -0
- package/docs/Reference/HTTP2.md +1 -3
- package/docs/Reference/Hooks.md +4 -1
- package/docs/Reference/Logging.md +1 -1
- package/docs/Reference/Reply.md +177 -0
- package/docs/Reference/Request.md +171 -0
- package/docs/Reference/Routes.md +6 -3
- package/docs/Reference/Server.md +20 -7
- package/docs/Reference/Validation-and-Serialization.md +1 -1
- package/fastify.d.ts +2 -2
- package/fastify.js +5 -5
- package/lib/configValidator.js +68 -19
- package/lib/contentTypeParser.js +10 -2
- package/lib/context.js +10 -1
- package/lib/errors.js +8 -0
- package/lib/handleRequest.js +2 -2
- package/lib/httpMethods.js +22 -0
- package/lib/reply.js +80 -2
- package/lib/reqIdGenFactory.js +13 -2
- package/lib/request.js +97 -1
- package/lib/route.js +4 -4
- package/lib/server.js +1 -0
- package/lib/symbols.js +15 -9
- package/package.json +3 -9
- package/test/content-parser.test.js +15 -0
- package/test/copy.test.js +41 -0
- package/test/internals/all.test.js +8 -2
- package/test/internals/reply-serialize.test.js +583 -0
- package/test/internals/reply.test.js +4 -1
- package/test/internals/request-validate.test.js +1269 -0
- package/test/internals/request.test.js +11 -2
- package/test/lock.test.js +73 -0
- package/test/logger.test.js +108 -0
- package/test/mkcol.test.js +38 -0
- package/test/move.test.js +45 -0
- package/test/propfind.test.js +108 -0
- package/test/proppatch.test.js +78 -0
- package/test/request-error.test.js +44 -1
- package/test/schema-examples.test.js +54 -0
- package/test/search.test.js +100 -0
- package/test/trace.test.js +21 -0
- package/test/types/fastify.test-d.ts +1 -0
- package/test/types/hooks.test-d.ts +1 -2
- package/test/types/import.ts +1 -1
- package/test/types/instance.test-d.ts +1 -1
- package/test/types/logger.test-d.ts +4 -5
- package/test/types/reply.test-d.ts +44 -3
- package/test/types/request.test-d.ts +10 -29
- package/test/types/type-provider.test-d.ts +79 -7
- package/test/unlock.test.js +41 -0
- package/test/upgrade.test.js +53 -0
- package/types/hooks.d.ts +19 -39
- package/types/instance.d.ts +20 -40
- package/types/logger.d.ts +7 -4
- package/types/reply.d.ts +7 -1
- package/types/request.d.ts +16 -3
- package/types/route.d.ts +23 -29
- package/types/type-provider.d.ts +8 -20
- package/types/utils.d.ts +2 -1
|
@@ -97,7 +97,7 @@ const schema = {
|
|
|
97
97
|
onProtoPoisoning: { type: 'string', default: defaultInitOptions.onProtoPoisoning },
|
|
98
98
|
onConstructorPoisoning: { type: 'string', default: defaultInitOptions.onConstructorPoisoning },
|
|
99
99
|
pluginTimeout: { type: 'integer', default: defaultInitOptions.pluginTimeout },
|
|
100
|
-
requestIdHeader: { type: 'string', default: defaultInitOptions.requestIdHeader },
|
|
100
|
+
requestIdHeader: { anyOf: [{ enum: [false] }, { type: 'string' }], default: defaultInitOptions.requestIdHeader },
|
|
101
101
|
requestIdLogLabel: { type: 'string', default: defaultInitOptions.requestIdLogLabel },
|
|
102
102
|
http2SessionTimeout: { type: 'integer', default: defaultInitOptions.http2SessionTimeout },
|
|
103
103
|
exposeHeadRoutes: { type: 'boolean', default: defaultInitOptions.exposeHeadRoutes },
|
package/docs/Guides/Ecosystem.md
CHANGED
|
@@ -112,6 +112,14 @@ section.
|
|
|
112
112
|
- [`@fastify/swagger`](https://github.com/fastify/fastify-swagger) Plugin for
|
|
113
113
|
serving Swagger/OpenAPI documentation for Fastify, supporting dynamic
|
|
114
114
|
generation.
|
|
115
|
+
- [`@fastify/type-provider-json-schema-to-ts`](https://github.com/fastify/fastify-type-provider-json-schema-to-ts)
|
|
116
|
+
Fastify
|
|
117
|
+
[type provider](https://www.fastify.io/docs/latest/Reference/Type-Providers/)
|
|
118
|
+
for [json-schema-to-ts](https://github.com/ThomasAribart/json-schema-to-ts).
|
|
119
|
+
- [`@fastify/type-provider-typebox`](https://github.com/fastify/fastify-type-provider-typebox)
|
|
120
|
+
Fastify
|
|
121
|
+
[type provider](https://www.fastify.io/docs/latest/Reference/Type-Providers/)
|
|
122
|
+
for [Typebox](https://github.com/sinclairzx81/typebox).
|
|
115
123
|
- [`@fastify/under-pressure`](https://github.com/fastify/under-pressure) Measure
|
|
116
124
|
process load with automatic handling of _"Service Unavailable"_ plugin for
|
|
117
125
|
Fastify.
|
|
@@ -147,6 +155,9 @@ section.
|
|
|
147
155
|
- [`@immobiliarelabs/fastify-sentry`](https://github.com/immobiliare/fastify-sentry)
|
|
148
156
|
Sentry errors handler that just works! Install, add your DSN and you're good
|
|
149
157
|
to go!
|
|
158
|
+
- [`@mateonunez/fastify-lyra`](https://github.com/mateonunez/fastify-lyra)
|
|
159
|
+
A plugin to implement [Lyra](https://github.com/nearform/lyra) search engine
|
|
160
|
+
on Fastify
|
|
150
161
|
- [`@mgcrea/fastify-graceful-exit`](https://github.com/mgcrea/fastify-graceful-exit)
|
|
151
162
|
A plugin to close the server gracefully
|
|
152
163
|
- [`@mgcrea/fastify-request-logger`](https://github.com/mgcrea/fastify-request-logger)
|
|
@@ -169,6 +180,8 @@ section.
|
|
|
169
180
|
- [`cls-rtracer`](https://github.com/puzpuzpuz/cls-rtracer) Fastify middleware
|
|
170
181
|
for CLS-based request ID generation. An out-of-the-box solution for adding
|
|
171
182
|
request IDs into your logs.
|
|
183
|
+
- [`electron-server`](https://github.com/anonrig/electron-server) A plugin for
|
|
184
|
+
using Fastify without the need of consuming a port on Electron apps.
|
|
172
185
|
- [`fast-water`](https://github.com/tswayne/fast-water) A Fastify plugin for
|
|
173
186
|
waterline. Decorates Fastify with waterline models.
|
|
174
187
|
- [`fastify-405`](https://github.com/Eomm/fastify-405) Fastify plugin that adds
|
|
@@ -213,6 +226,8 @@ section.
|
|
|
213
226
|
to add [boom](https://github.com/hapijs/boom) support.
|
|
214
227
|
- [`fastify-bree`](https://github.com/climba03003/fastify-bree) Fastify plugin
|
|
215
228
|
to add [bree](https://github.com/breejs/bree) support.
|
|
229
|
+
- [`fastify-bugsnag`](https://github.com/ZigaStrgar/fastify-bugsnag) Fastify plugin
|
|
230
|
+
to add support for [Bugsnag](https://www.bugsnag.com/) error reporting.
|
|
216
231
|
- [`fastify-casbin`](https://github.com/nearform/fastify-casbin) Casbin support
|
|
217
232
|
for Fastify.
|
|
218
233
|
- [`fastify-casbin-rest`](https://github.com/nearform/fastify-casbin-rest)
|
|
@@ -313,6 +328,8 @@ section.
|
|
|
313
328
|
- [`fastify-http2https`](https://github.com/lolo32/fastify-http2https) Redirect
|
|
314
329
|
HTTP requests to HTTPS, both using the same port number, or different response
|
|
315
330
|
on HTTP and HTTPS.
|
|
331
|
+
- [`fastify-https-always`](https://github.com/mattbishop/fastify-https-always)
|
|
332
|
+
Lightweight, proxy-aware redirect plugin from HTTP to HTTPS.
|
|
316
333
|
- [`fastify-https-redirect`](https://github.com/tomsvogel/fastify-https-redirect)
|
|
317
334
|
Fastify plugin for auto-redirect from HTTP to HTTPS.
|
|
318
335
|
- [`fastify-impressions`](https://github.com/manju4ever/fastify-impressions)
|
|
@@ -326,6 +343,8 @@ section.
|
|
|
326
343
|
authentication for Fastify-based web apps.
|
|
327
344
|
- [`fastify-kafkajs`](https://github.com/kffl/fastify-kafkajs) Fastify plugin
|
|
328
345
|
that adds support for KafkaJS - a modern Apache Kafka client library.
|
|
346
|
+
- [`fastify-keycloak-adapter`](https://github.com/yubinTW/fastify-keycloak-adapter)
|
|
347
|
+
A keycloak adapter for a Fastify app.
|
|
329
348
|
- [`fastify-knexjs`](https://github.com/chapuletta/fastify-knexjs) Fastify
|
|
330
349
|
plugin for support KnexJS Query Builder.
|
|
331
350
|
- [`fastify-knexjs-mock`](https://github.com/chapuletta/fastify-knexjs-mock)
|
|
@@ -409,6 +428,8 @@ section.
|
|
|
409
428
|
- [`fastify-orientdb`](https://github.com/mahmed8003/fastify-orientdb) Fastify
|
|
410
429
|
OrientDB connection plugin, with which you can share the OrientDB connection
|
|
411
430
|
across every part of your server.
|
|
431
|
+
- [`fastify-osm`](https://github.com/gzileni/fastify-osm) Fastify
|
|
432
|
+
OSM plugin to run overpass queries by OpenStreetMap.
|
|
412
433
|
- [`fastify-peekaboo`](https://github.com/simone-sanfratello/fastify-peekaboo)
|
|
413
434
|
Fastify plugin for memoize responses by expressive settings.
|
|
414
435
|
- [`fastify-piscina`](https://github.com/piscinajs/fastify-piscina) A worker
|
|
@@ -506,6 +527,10 @@ section.
|
|
|
506
527
|
TOTP (e.g. for 2FA).
|
|
507
528
|
- [`fastify-twitch-ebs-tools`](https://github.com/lukemnet/fastify-twitch-ebs-tools)
|
|
508
529
|
Useful functions for Twitch Extension Backend Services (EBS).
|
|
530
|
+
- [`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/)
|
|
533
|
+
for [zod](https://github.com/colinhacks/zod).
|
|
509
534
|
- [`fastify-typeorm-plugin`](https://github.com/inthepocket/fastify-typeorm-plugin)
|
|
510
535
|
Fastify plugin to work with TypeORM.
|
|
511
536
|
- [`fastify-vhost`](https://github.com/patrickpissurno/fastify-vhost) Proxy
|
package/docs/Reference/HTTP2.md
CHANGED
|
@@ -2,9 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## HTTP2
|
|
4
4
|
|
|
5
|
-
_Fastify_
|
|
6
|
-
which includes HTTP2 without a flag; HTTP2 is supported over either HTTPS or
|
|
7
|
-
plaintext.
|
|
5
|
+
_Fastify_ supports HTTP2 over either HTTPS (h2) or plaintext (h2c).
|
|
8
6
|
|
|
9
7
|
Currently, none of the HTTP2-specific APIs are available through _Fastify_, but
|
|
10
8
|
Node's `req` and `res` can be accessed through our `Request` and `Reply`
|
package/docs/Reference/Hooks.md
CHANGED
|
@@ -244,6 +244,9 @@ The `onResponse` hook is executed when a response has been sent, so you will not
|
|
|
244
244
|
be able to send more data to the client. It can however be useful for sending
|
|
245
245
|
data to external services, for example, to gather statistics.
|
|
246
246
|
|
|
247
|
+
**Note:** setting `disableRequestLogging` to `true` will disable any error log
|
|
248
|
+
inside the `onResponse` hook. In this case use `try - catch` to log errors.
|
|
249
|
+
|
|
247
250
|
### onTimeout
|
|
248
251
|
|
|
249
252
|
```js
|
|
@@ -287,7 +290,7 @@ fastify.addHook('preHandler', (request, reply, done) => {
|
|
|
287
290
|
|
|
288
291
|
Or if you're using `async/await` you can just throw an error:
|
|
289
292
|
```js
|
|
290
|
-
fastify.addHook('
|
|
293
|
+
fastify.addHook('onRequest', async (request, reply) => {
|
|
291
294
|
throw new Error('Some error')
|
|
292
295
|
})
|
|
293
296
|
```
|
|
@@ -170,7 +170,7 @@ app.addHook('preHandler', function (req, reply, done) {
|
|
|
170
170
|
You can also supply your own logger instance. Instead of passing configuration
|
|
171
171
|
options, pass the instance. The logger you supply must conform to the Pino
|
|
172
172
|
interface; that is, it must have the following methods: `info`, `error`,
|
|
173
|
-
`debug`, `fatal`, `warn`, `trace`, `child`.
|
|
173
|
+
`debug`, `fatal`, `warn`, `trace`, `silent`, `child` and a string property `level`.
|
|
174
174
|
|
|
175
175
|
Example:
|
|
176
176
|
|
package/docs/Reference/Reply.md
CHANGED
|
@@ -20,6 +20,9 @@
|
|
|
20
20
|
- [.callNotFound()](#callnotfound)
|
|
21
21
|
- [.getResponseTime()](#getresponsetime)
|
|
22
22
|
- [.type(contentType)](#typecontenttype)
|
|
23
|
+
- [.getSerializationFunction(schema | httpStatus)](#getserializationfunction)
|
|
24
|
+
- [.compileSerializationSchema(schema, httpStatus)](#compileserializationschema)
|
|
25
|
+
- [.serializeInput(data, [schema | httpStatus], [httpStatus])](#serializeinput)
|
|
23
26
|
- [.serializer(func)](#serializerfunc)
|
|
24
27
|
- [.raw](#raw)
|
|
25
28
|
- [.sent](#sent)
|
|
@@ -60,6 +63,16 @@ object that exposes the following functions and properties:
|
|
|
60
63
|
- `.serialize(payload)` - Serializes the specified payload using the default
|
|
61
64
|
JSON serializer or using the custom serializer (if one is set) and returns the
|
|
62
65
|
serialized payload.
|
|
66
|
+
- `.getSerializationFunction(schema | httpStatus)` - Returns the serialization
|
|
67
|
+
function for the specified schema or http status, if any of either are set.
|
|
68
|
+
- `.compileSerializationSchema(schema, httpStatus)` - Compiles the specified
|
|
69
|
+
schema and returns a serialization function using the default (or customized)
|
|
70
|
+
`SerializerCompiler`. The optional `httpStatus` is forwarded to the
|
|
71
|
+
`SerializerCompiler` if provided, default to `undefined`.
|
|
72
|
+
- `.serializeInput(data, schema, [,httpStatus])` - Serializes the specified data
|
|
73
|
+
using the specified schema and returns the serialized payload.
|
|
74
|
+
If the optional `httpStatus` is provided, the function will use the serializer
|
|
75
|
+
function given for that HTTP Status Code. Default to `undefined`.
|
|
63
76
|
- `.serializer(function)` - Sets a custom serializer for the payload.
|
|
64
77
|
- `.send(payload)` - Sends the payload to the user, could be a plain text, a
|
|
65
78
|
buffer, JSON, stream, or an Error object.
|
|
@@ -326,6 +339,169 @@ reply.type('text/html')
|
|
|
326
339
|
If the `Content-Type` has a JSON subtype, and the charset parameter is not set,
|
|
327
340
|
`utf-8` will be used as the charset by default.
|
|
328
341
|
|
|
342
|
+
### .getSerializationFunction(schema | httpStatus)
|
|
343
|
+
<a id="getserializationfunction"></a>
|
|
344
|
+
|
|
345
|
+
By calling this function using a provided `schema` or `httpStatus`,
|
|
346
|
+
it will return a `serialzation` function that can be used to
|
|
347
|
+
serialize diverse inputs. It returns `undefined` if no
|
|
348
|
+
serialization function was found using either of the provided inputs.
|
|
349
|
+
|
|
350
|
+
This heavily depends of the `schema#responses` attached to the route, or
|
|
351
|
+
the serialization functions compiled by using `compileSerializationSchema`.
|
|
352
|
+
|
|
353
|
+
```js
|
|
354
|
+
const serialize = reply
|
|
355
|
+
.getSerializationFunction({
|
|
356
|
+
type: 'object',
|
|
357
|
+
properties: {
|
|
358
|
+
foo: {
|
|
359
|
+
type: 'string'
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
})
|
|
363
|
+
serialize({ foo: 'bar' }) // '{"foo":"bar"}'
|
|
364
|
+
|
|
365
|
+
// or
|
|
366
|
+
|
|
367
|
+
const serialize = reply
|
|
368
|
+
.getSerializationFunction(200)
|
|
369
|
+
serialize({ foo: 'bar' }) // '{"foo":"bar"}'
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
See [.compileSerializationSchema(schema, [httpStatus])](#compileserializationschema)
|
|
373
|
+
for more information on how to compile serialization schemas.
|
|
374
|
+
|
|
375
|
+
### .compileSerializationSchema(schema, httpStatus)
|
|
376
|
+
<a id="compileserializationschema"></a>
|
|
377
|
+
|
|
378
|
+
This function will compile a serialization schema and
|
|
379
|
+
return a function that can be used to serialize data.
|
|
380
|
+
The function returned (a.k.a. _serialization function_) returned is compiled
|
|
381
|
+
by using the provided `SerializerCompiler`. Also this is cached by using
|
|
382
|
+
a `WeakMap` for reducing compilation calls.
|
|
383
|
+
|
|
384
|
+
The optional paramater `httpStatus`, if provided, is forwarded directly
|
|
385
|
+
the `SerializerCompiler`, so it can be used to compile the serialization
|
|
386
|
+
function if a custom `SerializerCompiler` is used.
|
|
387
|
+
|
|
388
|
+
This heavily depends of the `schema#responses` attached to the route, or
|
|
389
|
+
the serialization functions compiled by using `compileSerializationSchema`.
|
|
390
|
+
|
|
391
|
+
```js
|
|
392
|
+
const serialize = reply
|
|
393
|
+
.compileSerializationSchema({
|
|
394
|
+
type: 'object',
|
|
395
|
+
properties: {
|
|
396
|
+
foo: {
|
|
397
|
+
type: 'string'
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
})
|
|
401
|
+
serialize({ foo: 'bar' }) // '{"foo":"bar"}'
|
|
402
|
+
|
|
403
|
+
// or
|
|
404
|
+
|
|
405
|
+
const serialize = reply
|
|
406
|
+
.compileSerializationSchema({
|
|
407
|
+
type: 'object',
|
|
408
|
+
properties: {
|
|
409
|
+
foo: {
|
|
410
|
+
type: 'string'
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}, 200)
|
|
414
|
+
serialize({ foo: 'bar' }) // '{"foo":"bar"}'
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
Note that you should be careful when using this function, as it will cache
|
|
418
|
+
the compiled serialization functions based on the schema provided. If the
|
|
419
|
+
schemas provided is mutated or changed, the serialization functions will not
|
|
420
|
+
detect that the schema has been altered and for instance it will reuse the
|
|
421
|
+
previously compiled serialization function based on the reference of the schema
|
|
422
|
+
previously provided.
|
|
423
|
+
|
|
424
|
+
If there's a need to change the properties of a schema, always opt to create
|
|
425
|
+
a totally new object, otherwise the implementation won't benefit from the cache
|
|
426
|
+
mechanism.
|
|
427
|
+
|
|
428
|
+
:Using the following schema as example:
|
|
429
|
+
```js
|
|
430
|
+
const schema1 = {
|
|
431
|
+
type: 'object',
|
|
432
|
+
properties: {
|
|
433
|
+
foo: {
|
|
434
|
+
type: 'string'
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
*Not*
|
|
441
|
+
```js
|
|
442
|
+
const serialize = reply.compileSerializationSchema(schema1)
|
|
443
|
+
|
|
444
|
+
// Later on...
|
|
445
|
+
schema1.properties.foo.type. = 'integer'
|
|
446
|
+
const newSerialize = reply.compileSerializationSchema(schema1)
|
|
447
|
+
|
|
448
|
+
console.log(newSerialize === serialize) // true
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
*Instead*
|
|
452
|
+
```js
|
|
453
|
+
const serialize = reply.compileSerializationSchema(schema1)
|
|
454
|
+
|
|
455
|
+
// Later on...
|
|
456
|
+
const newSchema = Object.assign({}, schema1)
|
|
457
|
+
newSchema.properties.foo.type = 'integer'
|
|
458
|
+
|
|
459
|
+
const newSerialize = reply.compileSerializationSchema(newSchema)
|
|
460
|
+
|
|
461
|
+
console.log(newSerialize === serialize) // false
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
### .serializeInput(data, [schema | httpStatus], [httpStatus])
|
|
465
|
+
<a id="serializeinput"></a>
|
|
466
|
+
|
|
467
|
+
This function will serialize the input data based on the provided schema,
|
|
468
|
+
or http status code. If both provided, the `httpStatus` will take presedence.
|
|
469
|
+
|
|
470
|
+
If there is not a serialization function for a given `schema`, a new serialization
|
|
471
|
+
function will be compiled forwarding the `httpStatus` if provided.
|
|
472
|
+
|
|
473
|
+
```js
|
|
474
|
+
reply
|
|
475
|
+
.serializeInput({ foo: 'bar'}, {
|
|
476
|
+
type: 'object',
|
|
477
|
+
properties: {
|
|
478
|
+
foo: {
|
|
479
|
+
type: 'string'
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
}) // '{"foo":"bar"}'
|
|
483
|
+
|
|
484
|
+
// or
|
|
485
|
+
|
|
486
|
+
reply
|
|
487
|
+
.serializeInput({ foo: 'bar'}, {
|
|
488
|
+
type: 'object',
|
|
489
|
+
properties: {
|
|
490
|
+
foo: {
|
|
491
|
+
type: 'string'
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}, 200) // '{"foo":"bar"}'
|
|
495
|
+
|
|
496
|
+
// or
|
|
497
|
+
|
|
498
|
+
reply
|
|
499
|
+
.serializeInput({ foo: 'bar'}, 200) // '{"foo":"bar"}'
|
|
500
|
+
```
|
|
501
|
+
|
|
502
|
+
See [.compileSerializationSchema(schema, [httpStatus])](#compileserializationschema)
|
|
503
|
+
for more information on how to compile serialization schemas.
|
|
504
|
+
|
|
329
505
|
### .serializer(func)
|
|
330
506
|
<a id="serializer"></a>
|
|
331
507
|
|
|
@@ -591,6 +767,7 @@ Fastify natively handles promises and supports async-await.
|
|
|
591
767
|
|
|
592
768
|
*Note that in the following examples we are not using reply.send.*
|
|
593
769
|
```js
|
|
770
|
+
const { promisify } = require('util')
|
|
594
771
|
const delay = promisify(setTimeout)
|
|
595
772
|
|
|
596
773
|
fastify.get('/promises', options, function (request, reply) {
|
|
@@ -35,6 +35,19 @@ 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
|
+
- [.getValidationFunction(schema | httpPart)](#getvalidationfunction) -
|
|
39
|
+
Returns a validation function for the specified schema or http part,
|
|
40
|
+
if any of either are set or cached.
|
|
41
|
+
- [.compileValidationSchema(schema, [httpPart])](#compilevalidationschema) -
|
|
42
|
+
Compiles the specified schema and returns a validation function
|
|
43
|
+
using the default (or customized) `ValidationCompiler`.
|
|
44
|
+
The optional `httpPart` is forwarded to the `ValidationCompiler`
|
|
45
|
+
if provided, defaults to `null`.
|
|
46
|
+
- [.validateInput(data, schema | httpPart, [httpPart])](#validate) -
|
|
47
|
+
Validates the specified input by using the specified
|
|
48
|
+
schema and returns the serialized payload. If the optional
|
|
49
|
+
`httpPart` is provided, the function will use the serializer
|
|
50
|
+
function given for that HTTP Status Code. Defaults to `null`.
|
|
38
51
|
- `context` - A Fastify internal object. You should not use it directly or
|
|
39
52
|
modify it. It is useful to access one special key:
|
|
40
53
|
- `context.config` - The route [`config`](./Routes.md#routes-config) object.
|
|
@@ -77,3 +90,161 @@ fastify.post('/:params', options, function (request, reply) {
|
|
|
77
90
|
request.log.info('some info')
|
|
78
91
|
})
|
|
79
92
|
```
|
|
93
|
+
### .getValidationFunction(schema | httpPart)
|
|
94
|
+
<a id="getvalidationfunction"></a>
|
|
95
|
+
|
|
96
|
+
By calling this function using a provided `schema` or `httpPart`,
|
|
97
|
+
it will return a `validation` function that can be used to
|
|
98
|
+
validate diverse inputs. It returns `undefined` if no
|
|
99
|
+
serialization function was found using either of the provided inputs.
|
|
100
|
+
|
|
101
|
+
```js
|
|
102
|
+
const validate = request
|
|
103
|
+
.getValidationFunction({
|
|
104
|
+
type: 'object',
|
|
105
|
+
properties: {
|
|
106
|
+
foo: {
|
|
107
|
+
type: 'string'
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
})
|
|
111
|
+
validate({ foo: 'bar' }) // true
|
|
112
|
+
|
|
113
|
+
// or
|
|
114
|
+
|
|
115
|
+
const validate = request
|
|
116
|
+
.getValidationFunction('body')
|
|
117
|
+
validate({ foo: 0.5 }) // false
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
See [.compilaValidationSchema(schema, [httpStatus])](#compilevalidationschema)
|
|
121
|
+
for more information on how to compile validation function.
|
|
122
|
+
|
|
123
|
+
### .compileValidationSchema(schema, [httpPart])
|
|
124
|
+
<a id="compilevalidationschema"></a>
|
|
125
|
+
|
|
126
|
+
This function will compile a validation schema and
|
|
127
|
+
return a function that can be used to validate data.
|
|
128
|
+
The function returned (a.k.a. _validation function_) is compiled
|
|
129
|
+
by using the provided [`SchemaControler#ValidationCompiler`](./Server.md#schema-controller).
|
|
130
|
+
A `WeakMap` is used to cached this, reducing compilation calls.
|
|
131
|
+
|
|
132
|
+
The optional parameter `httpPart`, if provided, is forwarded directly
|
|
133
|
+
the `ValidationCompiler`, so it can be used to compile the validation
|
|
134
|
+
function if a custom `ValidationCompiler` is provided for the route.
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
```js
|
|
138
|
+
const validate = request
|
|
139
|
+
.compileValidationSchema({
|
|
140
|
+
type: 'object',
|
|
141
|
+
properties: {
|
|
142
|
+
foo: {
|
|
143
|
+
type: 'string'
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
})
|
|
147
|
+
console.log(validate({ foo: 'bar' })) // true
|
|
148
|
+
|
|
149
|
+
// or
|
|
150
|
+
|
|
151
|
+
const validate = request
|
|
152
|
+
.compileValidationSchema({
|
|
153
|
+
type: 'object',
|
|
154
|
+
properties: {
|
|
155
|
+
foo: {
|
|
156
|
+
type: 'string'
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}, 200)
|
|
160
|
+
console.log(validate({ hello: 'world' })) // false
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Note that you should be careful when using this function, as it will cache
|
|
164
|
+
the compiled validation functions based on the schema provided. If the
|
|
165
|
+
schemas provided are mutated or changed, the validation functions will not
|
|
166
|
+
detect that the schema has been altered and for instance it will reuse the
|
|
167
|
+
previously compiled validation function, as the cache is based on
|
|
168
|
+
the reference of the schema (Object) previously provided.
|
|
169
|
+
|
|
170
|
+
If there is a need to change the properties of a schema, always opt to create
|
|
171
|
+
a totally new schema (object), otherwise the implementation will not benefit from
|
|
172
|
+
the cache mechanism.
|
|
173
|
+
|
|
174
|
+
Using the following schema as an example:
|
|
175
|
+
```js
|
|
176
|
+
const schema1 = {
|
|
177
|
+
type: 'object',
|
|
178
|
+
properties: {
|
|
179
|
+
foo: {
|
|
180
|
+
type: 'string'
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
*Not*
|
|
187
|
+
```js
|
|
188
|
+
const validate = request.compileValidationSchema(schema1)
|
|
189
|
+
|
|
190
|
+
// Later on...
|
|
191
|
+
schema1.properties.foo.type. = 'integer'
|
|
192
|
+
const newValidate = request.compileValidationSchema(schema1)
|
|
193
|
+
|
|
194
|
+
console.log(newValidate === validate) // true
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
*Instead*
|
|
198
|
+
```js
|
|
199
|
+
const validate = request.compileValidationSchema(schema1)
|
|
200
|
+
|
|
201
|
+
// Later on...
|
|
202
|
+
const newSchema = Object.assign({}, schema1)
|
|
203
|
+
newSchema.properties.foo.type = 'integer'
|
|
204
|
+
|
|
205
|
+
const newValidate = request.compileValidationSchema(newSchema)
|
|
206
|
+
|
|
207
|
+
console.log(newValidate === validate) // false
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
### .validateInput(data, [schema | httpStatus], [httpStatus])
|
|
211
|
+
<a id="validate"></a>
|
|
212
|
+
|
|
213
|
+
This function will validate the input based on the provided schema,
|
|
214
|
+
or HTTP part passed. If both are provided, the `httpPart` parameter
|
|
215
|
+
will take precedence.
|
|
216
|
+
|
|
217
|
+
If there is not a validation function for a given `schema`, a new validation
|
|
218
|
+
function will be compiled, forwarding the `httpPart` if provided.
|
|
219
|
+
|
|
220
|
+
```js
|
|
221
|
+
request
|
|
222
|
+
.validateInput({ foo: 'bar'}, {
|
|
223
|
+
type: 'object',
|
|
224
|
+
properties: {
|
|
225
|
+
foo: {
|
|
226
|
+
type: 'string'
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}) // true
|
|
230
|
+
|
|
231
|
+
// or
|
|
232
|
+
|
|
233
|
+
request
|
|
234
|
+
.validateInput({ foo: 'bar'}, {
|
|
235
|
+
type: 'object',
|
|
236
|
+
properties: {
|
|
237
|
+
foo: {
|
|
238
|
+
type: 'string'
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}, 'body') // true
|
|
242
|
+
|
|
243
|
+
// or
|
|
244
|
+
|
|
245
|
+
request
|
|
246
|
+
.validateInput({ hello: 'world'}, 'query') // false
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
See [.compileValidationSchema(schema, [httpStatus])](#compileValidationSchema)
|
|
250
|
+
for more information on how to compile validation schemas.
|
package/docs/Reference/Routes.md
CHANGED
|
@@ -32,8 +32,10 @@ fastify.route(options)
|
|
|
32
32
|
### Routes options
|
|
33
33
|
<a id="options"></a>
|
|
34
34
|
|
|
35
|
-
|
|
36
|
-
`'POST'`, `'PUT'
|
|
35
|
+
* `method`: currently it supports `'DELETE'`, `'GET'`, `'HEAD'`, `'PATCH'`,
|
|
36
|
+
`'POST'`, `'PUT'`, `'OPTIONS'`, `'SEARCH'`, `'TRACE'`, `'PROPFIND'`,
|
|
37
|
+
`'PROPPATCH'`, `'MKCOL'`, `'COPY'`, `'MOVE'`, `'LOCK'` and `'UNLOCK'`.
|
|
38
|
+
It could also be an array of methods.
|
|
37
39
|
* `url`: the path of the URL to match this route (alias: `path`).
|
|
38
40
|
* `schema`: an object containing the schemas for the request and response. They
|
|
39
41
|
need to be in [JSON Schema](https://json-schema.org/) format, check
|
|
@@ -656,7 +658,7 @@ fastify.inject({
|
|
|
656
658
|
>
|
|
657
659
|
> ```js
|
|
658
660
|
> const append = require('vary').append
|
|
659
|
-
> fastify.addHook('onSend',
|
|
661
|
+
> fastify.addHook('onSend', (req, reply, payload, done) => {
|
|
660
662
|
> if (req.headers['accept-version']) { // or the custom header you are using
|
|
661
663
|
> let value = reply.getHeader('Vary') || ''
|
|
662
664
|
> const header = Array.isArray(value) ? value.join(', ') : String(value)
|
|
@@ -664,6 +666,7 @@ fastify.inject({
|
|
|
664
666
|
> reply.header('Vary', value)
|
|
665
667
|
> }
|
|
666
668
|
> }
|
|
669
|
+
> done()
|
|
667
670
|
> })
|
|
668
671
|
> ```
|
|
669
672
|
|
package/docs/Reference/Server.md
CHANGED
|
@@ -55,7 +55,7 @@ describes the properties available in that options object.
|
|
|
55
55
|
- [routing](#routing)
|
|
56
56
|
- [route](#route)
|
|
57
57
|
- [close](#close)
|
|
58
|
-
- [decorate
|
|
58
|
+
- [decorate*](#decorate)
|
|
59
59
|
- [register](#register)
|
|
60
60
|
- [addHook](#addhook)
|
|
61
61
|
- [prefix](#prefix)
|
|
@@ -488,11 +488,18 @@ about safe regexp: [Safe-regex2](https://www.npmjs.com/package/safe-regex2)
|
|
|
488
488
|
### `requestIdHeader`
|
|
489
489
|
<a id="factory-request-id-header"></a>
|
|
490
490
|
|
|
491
|
-
The header name used to
|
|
491
|
+
The header name used to set the request-id. See [the
|
|
492
492
|
request-id](./Logging.md#logging-request-id) section.
|
|
493
|
+
Setting `requestIdHeader` to `false` will always use [genReqId](#genreqid)
|
|
493
494
|
|
|
494
495
|
+ Default: `'request-id'`
|
|
495
|
-
|
|
496
|
+
|
|
497
|
+
```js
|
|
498
|
+
const fastify = require('fastify')({
|
|
499
|
+
requestIdHeader: 'x-custom-id', // -> use 'X-Custom-Id' header if available
|
|
500
|
+
//requestIdHeader: false, // -> always use genReqId
|
|
501
|
+
})
|
|
502
|
+
```
|
|
496
503
|
### `requestIdLogLabel`
|
|
497
504
|
<a id="factory-request-id-log-label"></a>
|
|
498
505
|
|
|
@@ -890,7 +897,7 @@ fastify.ready().then(() => {
|
|
|
890
897
|
Starts the server and internally waits for the `.ready()` event. The signature
|
|
891
898
|
is `.listen([options][, callback])`. Both the `options` object and the
|
|
892
899
|
`callback` parameters follow the [Node.js
|
|
893
|
-
core]
|
|
900
|
+
core](https://nodejs.org/api/net.html#serverlistenoptions-callback) parameter
|
|
894
901
|
definitions.
|
|
895
902
|
|
|
896
903
|
By default, the server will listen on the address(es) resolved by `localhost`
|
|
@@ -1112,12 +1119,15 @@ fastify.register(function (instance, opts, done) {
|
|
|
1112
1119
|
<a id="pluginName"></a>
|
|
1113
1120
|
|
|
1114
1121
|
Name of the current plugin. The root plugin is called `'fastify'`. There are
|
|
1115
|
-
|
|
1122
|
+
different ways to define a name (in order).
|
|
1116
1123
|
|
|
1117
1124
|
1. If you use [fastify-plugin](https://github.com/fastify/fastify-plugin) the
|
|
1118
1125
|
metadata `name` is used.
|
|
1119
|
-
2. If
|
|
1120
|
-
|
|
1126
|
+
2. If the exported plugin has the `Symbol.for('fastify.display-name')` property,
|
|
1127
|
+
then the value of that property is used.
|
|
1128
|
+
Example: `pluginFn[Symbol.for('fastify.display-name')] = "Custom Name"`
|
|
1129
|
+
3. If you `module.exports` a plugin the filename is used.
|
|
1130
|
+
4. If you use a regular [function
|
|
1121
1131
|
declaration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Defining_functions)
|
|
1122
1132
|
the function name is used.
|
|
1123
1133
|
|
|
@@ -1402,6 +1412,9 @@ handlers. *async-await* is supported as well.
|
|
|
1402
1412
|
*Note: If the error `statusCode` is less than 400, Fastify will automatically
|
|
1403
1413
|
set it at 500 before calling the error handler.*
|
|
1404
1414
|
|
|
1415
|
+
*Also note* that `setErrorHandler` will ***not*** catch any error inside
|
|
1416
|
+
an `onResponse` hook because the response has already been sent to the client.
|
|
1417
|
+
|
|
1405
1418
|
```js
|
|
1406
1419
|
fastify.setErrorHandler(function (error, request, reply) {
|
|
1407
1420
|
// Log error
|
|
@@ -268,7 +268,7 @@ fastify.listen({ port: 3000 }, (err) => {
|
|
|
268
268
|
```sh
|
|
269
269
|
curl -X GET "http://localhost:3000/?ids=1
|
|
270
270
|
|
|
271
|
-
{"params":{"
|
|
271
|
+
{"params":{"ids":["1"]}}
|
|
272
272
|
```
|
|
273
273
|
|
|
274
274
|
You can also specify a custom schema validator for each parameter type (body,
|
package/fastify.d.ts
CHANGED
|
@@ -123,7 +123,7 @@ export type FastifyServerOptions<
|
|
|
123
123
|
serializerOpts?: FJSOptions | Record<string, unknown>,
|
|
124
124
|
serverFactory?: FastifyServerFactory<RawServer>,
|
|
125
125
|
caseSensitive?: boolean,
|
|
126
|
-
requestIdHeader?: string,
|
|
126
|
+
requestIdHeader?: string | false,
|
|
127
127
|
requestIdLogLabel?: string;
|
|
128
128
|
jsonShorthand?: boolean;
|
|
129
129
|
genReqId?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault>(req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>, FastifySchema, TypeProvider>) => string,
|
|
@@ -194,7 +194,7 @@ export type { Chain as LightMyRequestChain, InjectOptions, Response as LightMyRe
|
|
|
194
194
|
export { FastifyRequest, RequestGenericInterface } from './types/request'
|
|
195
195
|
export { FastifyReply } from './types/reply'
|
|
196
196
|
export { FastifyPluginCallback, FastifyPluginAsync, FastifyPluginOptions, FastifyPlugin } from './types/plugin'
|
|
197
|
-
export { FastifyInstance, PrintRoutesOptions } from './types/instance'
|
|
197
|
+
export { FastifyListenOptions, FastifyInstance, PrintRoutesOptions } from './types/instance'
|
|
198
198
|
export { FastifyLoggerOptions, FastifyBaseLogger, FastifyLoggerInstance, FastifyLogFn, LogLevel } from './types/logger'
|
|
199
199
|
export { FastifyContext, FastifyContextConfig } from './types/context'
|
|
200
200
|
export { RouteHandler, RouteHandlerMethod, RouteOptions, RouteShorthandMethod, RouteShorthandOptions, RouteShorthandOptionsWithHandler } from './types/route'
|