fastify 4.2.0 → 4.4.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.
Files changed (63) hide show
  1. package/README.md +13 -14
  2. package/docs/Guides/Database.md +2 -2
  3. package/docs/Guides/Ecosystem.md +42 -18
  4. package/docs/Guides/Migration-Guide-V4.md +29 -0
  5. package/docs/Guides/Plugins-Guide.md +5 -0
  6. package/docs/Reference/HTTP2.md +1 -3
  7. package/docs/Reference/Hooks.md +4 -1
  8. package/docs/Reference/Logging.md +1 -1
  9. package/docs/Reference/Reply.md +177 -0
  10. package/docs/Reference/Request.md +171 -0
  11. package/docs/Reference/Routes.md +4 -2
  12. package/docs/Reference/Server.md +4 -1
  13. package/docs/Reference/Type-Providers.md +1 -15
  14. package/docs/Reference/TypeScript.md +27 -3
  15. package/fastify.d.ts +1 -1
  16. package/fastify.js +3 -3
  17. package/lib/contentTypeParser.js +10 -2
  18. package/lib/context.js +10 -1
  19. package/lib/error-serializer.js +12 -12
  20. package/lib/errors.js +8 -0
  21. package/lib/handleRequest.js +2 -2
  22. package/lib/httpMethods.js +22 -0
  23. package/lib/reply.js +101 -24
  24. package/lib/request.js +97 -1
  25. package/lib/route.js +3 -1
  26. package/lib/symbols.js +15 -9
  27. package/package.json +7 -7
  28. package/test/build/error-serializer.test.js +3 -1
  29. package/test/content-parser.test.js +15 -0
  30. package/test/copy.test.js +41 -0
  31. package/test/internals/all.test.js +8 -2
  32. package/test/internals/reply-serialize.test.js +583 -0
  33. package/test/internals/reply.test.js +4 -1
  34. package/test/internals/request-validate.test.js +1269 -0
  35. package/test/internals/request.test.js +11 -2
  36. package/test/lock.test.js +73 -0
  37. package/test/mkcol.test.js +38 -0
  38. package/test/move.test.js +45 -0
  39. package/test/propfind.test.js +108 -0
  40. package/test/proppatch.test.js +78 -0
  41. package/test/request-error.test.js +44 -1
  42. package/test/schema-validation.test.js +71 -0
  43. package/test/search.test.js +100 -0
  44. package/test/trace.test.js +21 -0
  45. package/test/types/fastify.test-d.ts +12 -1
  46. package/test/types/hooks.test-d.ts +1 -2
  47. package/test/types/import.ts +1 -1
  48. package/test/types/instance.test-d.ts +4 -1
  49. package/test/types/logger.test-d.ts +4 -5
  50. package/test/types/reply.test-d.ts +44 -3
  51. package/test/types/request.test-d.ts +10 -29
  52. package/test/types/type-provider.test-d.ts +79 -7
  53. package/test/unlock.test.js +41 -0
  54. package/test/validation-error-handling.test.js +6 -1
  55. package/types/hooks.d.ts +19 -39
  56. package/types/instance.d.ts +78 -130
  57. package/types/logger.d.ts +7 -4
  58. package/types/reply.d.ts +7 -1
  59. package/types/request.d.ts +16 -3
  60. package/types/route.d.ts +23 -29
  61. package/types/schema.d.ts +4 -1
  62. package/types/type-provider.d.ts +8 -20
  63. package/types/utils.d.ts +2 -1
package/README.md CHANGED
@@ -38,18 +38,18 @@ resources of your server, knowing that you are serving the highest number of
38
38
  requests as possible, without sacrificing security validations and handy
39
39
  development?
40
40
 
41
- - [Quick start](./README.md#quick-start)
42
- - [Install](./README.md#install)
43
- - [Example](./README.md#example)
44
- - [Fastify v1.x and v2.x](./README.md#fastify-v1x-and-v2x)
45
- - [Core features](./README.md#core-features)
46
- - [Benchmarks](./README.md#benchmarks)
47
- - [Documentation](./README.md#documentation)
48
- - [Ecosystem](./README.md#ecosystem)
49
- - [Support](./README.md#support)
50
- - [Team](./README.md#team)
51
- - [Hosted by](./README.md#hosted-by)
52
- - [License](./README.md#license)
41
+ - [Quick start](#quick-start)
42
+ - [Install](#install)
43
+ - [Example](#example)
44
+ - [Fastify v1.x and v2.x](#fastify-v1x-and-v2x)
45
+ - [Core features](#core-features)
46
+ - [Benchmarks](#benchmarks)
47
+ - [Documentation](#documentation)
48
+ - [Ecosystem](#ecosystem)
49
+ - [Support](#support)
50
+ - [Team](#team)
51
+ - [Hosted by](#hosted-by)
52
+ - [License](#license)
53
53
 
54
54
  Enter Fastify. Fastify is a web framework highly focused on providing the best
55
55
  developer experience with the least overhead and a powerful plugin architecture.
@@ -99,8 +99,7 @@ generate functionality of [Fastify CLI](https://github.com/fastify/fastify-cli).
99
99
 
100
100
  ### Install
101
101
 
102
- If installing in an existing project, then Fastify can be installed into the
103
- project as a dependency:
102
+ To install Fastify in an existing project as a dependency:
104
103
 
105
104
  Install with npm:
106
105
  ```sh
@@ -204,7 +204,7 @@ function knexPlugin(fastify, options, done) {
204
204
  done()
205
205
  }
206
206
 
207
- export default fp(plugin, { name: 'fastify-knex-example' })
207
+ export default fp(knexPlugin, { name: 'fastify-knex-example' })
208
208
  ```
209
209
 
210
210
  ### Writing a plugin for a database engine
@@ -213,7 +213,7 @@ In this example, we will create a basic Fastify MySQL plugin from scratch (it is
213
213
  a stripped-down example, please use the official plugin in production).
214
214
 
215
215
  ```javascript
216
- const fp = require('fp')
216
+ const fp = require('fastify-plugin')
217
217
  const mysql = require('mysql2/promise')
218
218
 
219
219
  function fastifyMysql(fastify, options, done) {
@@ -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.
@@ -138,8 +146,8 @@ section.
138
146
  Tiny (~5k), Fast, KISS, and dependency-free Node.JS library to make your
139
147
  Fastify API graceful.
140
148
  - [`@h4ad/serverless-adapter`](https://github.com/H4ad/serverless-adapter)
141
- Run REST APIs and other web applications using your existing Node.js
142
- application framework (Express, Koa, Hapi and Fastify), on top of AWS Lambda,
149
+ Run REST APIs and other web applications using your existing Node.js
150
+ application framework (Express, Koa, Hapi and Fastify), on top of AWS Lambda,
143
151
  Huawei and many other clouds.
144
152
  - [`@immobiliarelabs/fastify-metrics`](https://github.com/immobiliare/fastify-metrics)
145
153
  Minimalistic and opinionated plugin that collects usage/process metrics and
@@ -147,16 +155,19 @@ 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)
153
164
  A plugin to enable compact request logging for Fastify
165
+ - [`@mgcrea/fastify-session`](https://github.com/mgcrea/fastify-session) Session
166
+ plugin for Fastify that supports both stateless and stateful sessions
154
167
  - [`@mgcrea/fastify-session-redis-store`](https://github.com/mgcrea/fastify-session-redis-store)
155
168
  Redis store for @mgcrea/fastify-session using ioredis
156
169
  - [`@mgcrea/fastify-session-sodium-crypto`](https://github.com/mgcrea/fastify-session-sodium-crypto)
157
170
  Fast sodium-based crypto for @mgcrea/fastify-session
158
- - [`@mgcrea/fastify-session`](https://github.com/mgcrea/fastify-session) Session
159
- plugin for Fastify that supports both stateless and stateful sessions
160
171
  - [`@mgcrea/pino-pretty-compact`](https://github.com/mgcrea/pino-pretty-compact)
161
172
  A custom compact pino-base prettifier
162
173
  - [`@trubavuong/fastify-seaweedfs`](https://github.com/trubavuong/fastify-seaweedfs)
@@ -169,6 +180,10 @@ 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.
185
+ - [`fast-water`](https://github.com/tswayne/fast-water) A Fastify plugin for
186
+ waterline. Decorates Fastify with waterline models.
172
187
  - [`fastify-405`](https://github.com/Eomm/fastify-405) Fastify plugin that adds
173
188
  405 HTTP status to your routes
174
189
  - [`fastify-allow`](https://github.com/mattbishop/fastify-allow) Fastify plugin
@@ -211,6 +226,8 @@ section.
211
226
  to add [boom](https://github.com/hapijs/boom) support.
212
227
  - [`fastify-bree`](https://github.com/climba03003/fastify-bree) Fastify plugin
213
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.
214
231
  - [`fastify-casbin`](https://github.com/nearform/fastify-casbin) Casbin support
215
232
  for Fastify.
216
233
  - [`fastify-casbin-rest`](https://github.com/nearform/fastify-casbin-rest)
@@ -287,13 +304,13 @@ section.
287
304
  good Fastify sessions plugin focused on speed.
288
305
  - [`fastify-google-cloud-storage`](https://github.com/carlozamagni/fastify-google-cloud-storage)
289
306
  Fastify plugin that exposes a GCP Cloud Storage client instance.
307
+ - [`fastify-graceful-shutdown`](https://github.com/hemerajs/fastify-graceful-shutdown)
308
+ Shutdown Fastify gracefully and asynchronously.
290
309
  - [`fastify-grant`](https://github.com/simov/fastify-grant)
291
310
  Authentication/Authorization plugin for Fastify that supports 200+ OAuth
292
311
  Providers.
293
312
  - [`fastify-guard`](https://github.com/hsynlms/fastify-guard) A Fastify plugin
294
313
  that protects endpoints by checking authenticated user roles and/or scopes.
295
- - [`fastify-graceful-shutdown`](https://github.com/hemerajs/fastify-graceful-shutdown)
296
- Shutdown Fastify gracefully and asynchronously.
297
314
  - [`fastify-hasura`](https://github.com/ManUtopiK/fastify-hasura) A Fastify
298
315
  plugin to have fun with [Hasura](https://github.com/hasura/graphql-engine).
299
316
  - [`fastify-healthcheck`](https://github.com/smartiniOnGitHub/fastify-healthcheck)
@@ -301,20 +318,19 @@ section.
301
318
  - [`fastify-hemera`](https://github.com/hemerajs/fastify-hemera) Fastify Hemera
302
319
  plugin, for writing reliable & fault-tolerant microservices with
303
320
  [nats.io](https://nats.io/).
321
+ - [`fastify-http-client`](https://github.com/kenuyx/fastify-http-client) Plugin
322
+ to send HTTP(s) requests. Built upon [urllib](https://github.com/node-modules/urllib).
304
323
  - [`fastify-http-context`](https://github.com/thorough-developer/fastify-http-context)
305
324
  Fastify plugin for "simulating" a thread of execution to allow for true HTTP
306
325
  context to take place per API call within the Fastify lifecycle of calls.
326
+ - [`fastify-http-errors-enhanced`](https://github.com/ShogunPanda/fastify-http-errors-enhanced)
327
+ An error handling plugin for Fastify that uses enhanced HTTP errors.
307
328
  - [`fastify-http2https`](https://github.com/lolo32/fastify-http2https) Redirect
308
329
  HTTP requests to HTTPS, both using the same port number, or different response
309
330
  on HTTP and HTTPS.
310
- - [`fastify-http-client`](https://github.com/kenuyx/fastify-http-client) Plugin
311
- to send HTTP(s) requests. Built upon
312
- [urllib](https://github.com/node-modules/urllib).
313
- - [`fastify-http-errors-enhanced`](https://github.com/ShogunPanda/fastify-http-errors-enhanced)
314
- An error handling plugin for Fastify that uses enhanced HTTP errors.
315
331
  - [`fastify-https-redirect`](https://github.com/tomsvogel/fastify-https-redirect)
316
332
  Fastify plugin for auto-redirect from HTTP to HTTPS.
317
- - [`fatify-impressions`](https://github.com/manju4ever/fastify-impressions)
333
+ - [`fastify-impressions`](https://github.com/manju4ever/fastify-impressions)
318
334
  Fastify plugin to track impressions of all the routes.
319
335
  - [`fastify-influxdb`](https://github.com/alex-ppg/fastify-influxdb) Fastify
320
336
  InfluxDB plugin connecting to an InfluxDB instance via the Influx default
@@ -325,6 +341,8 @@ section.
325
341
  authentication for Fastify-based web apps.
326
342
  - [`fastify-kafkajs`](https://github.com/kffl/fastify-kafkajs) Fastify plugin
327
343
  that adds support for KafkaJS - a modern Apache Kafka client library.
344
+ - [`fastify-keycloak-adapter`](https://github.com/yubinTW/fastify-keycloak-adapter)
345
+ A keycloak adapter for a Fastify app.
328
346
  - [`fastify-knexjs`](https://github.com/chapuletta/fastify-knexjs) Fastify
329
347
  plugin for support KnexJS Query Builder.
330
348
  - [`fastify-knexjs-mock`](https://github.com/chapuletta/fastify-knexjs-mock)
@@ -408,10 +426,10 @@ section.
408
426
  - [`fastify-orientdb`](https://github.com/mahmed8003/fastify-orientdb) Fastify
409
427
  OrientDB connection plugin, with which you can share the OrientDB connection
410
428
  across every part of your server.
411
- - [`fastify-piscina`](https://github.com/piscinajs/fastify-piscina) A worker
412
- thread pool plugin using [Piscina](https://github.com/piscinajs/piscina).
413
429
  - [`fastify-peekaboo`](https://github.com/simone-sanfratello/fastify-peekaboo)
414
430
  Fastify plugin for memoize responses by expressive settings.
431
+ - [`fastify-piscina`](https://github.com/piscinajs/fastify-piscina) A worker
432
+ thread pool plugin using [Piscina](https://github.com/piscinajs/piscina).
415
433
  - [`fastify-polyglot`](https://github.com/heply/fastify-polyglot) A plugin to
416
434
  handle i18n using
417
435
  [node-polyglot](https://www.npmjs.com/package/node-polyglot).
@@ -444,10 +462,10 @@ section.
444
462
  - [`fastify-register-routes`](https://github.com/israeleriston/fastify-register-routes)
445
463
  Plugin to automatically load routes from a specified path and optionally limit
446
464
  loaded file names by a regular expression.
447
- - [`fastify-response-time`](https://github.com/lolo32/fastify-response-time) Add
448
- `X-Response-Time` header at each request for Fastify, in milliseconds.
449
465
  - [`fastify-response-caching`](https://github.com/codeaholicguy/fastify-response-caching)
450
466
  A Fastify plugin for caching the response.
467
+ - [`fastify-response-time`](https://github.com/lolo32/fastify-response-time) Add
468
+ `X-Response-Time` header at each request for Fastify, in milliseconds.
451
469
  - [`fastify-resty`](https://github.com/FastifyResty/fastify-resty) Fastify-based
452
470
  web framework with REST API routes auto-generation for TypeORM entities using
453
471
  DI and decorators.
@@ -505,6 +523,10 @@ section.
505
523
  TOTP (e.g. for 2FA).
506
524
  - [`fastify-twitch-ebs-tools`](https://github.com/lukemnet/fastify-twitch-ebs-tools)
507
525
  Useful functions for Twitch Extension Backend Services (EBS).
526
+ - [`fastify-type-provider-zod`](https://github.com/turkerdev/fastify-type-provider-zod)
527
+ Fastify
528
+ [type provider](https://www.fastify.io/docs/latest/Reference/Type-Providers/)
529
+ for [zod](https://github.com/colinhacks/zod).
508
530
  - [`fastify-typeorm-plugin`](https://github.com/inthepocket/fastify-typeorm-plugin)
509
531
  Fastify plugin to work with TypeORM.
510
532
  - [`fastify-vhost`](https://github.com/patrickpissurno/fastify-vhost) Proxy
@@ -518,8 +540,6 @@ section.
518
540
  should use.
519
541
  - [`fastify-wamp-router`](https://github.com/lependu/fastify-wamp-router) Web
520
542
  Application Messaging Protocol router for Fastify.
521
- - [`fast-water`](https://github.com/tswayne/fast-water) A Fastify plugin for
522
- waterline. Decorates Fastify with waterline models.
523
543
  - [`fastify-webpack-hmr`](https://github.com/lependu/fastify-webpack-hmr)
524
544
  Webpack hot module reloading plugin for Fastify.
525
545
  - [`fastify-webpack-hot`](https://github.com/gajus/fastify-webpack-hot) Webpack
@@ -552,7 +572,11 @@ section.
552
572
  Fastify.
553
573
  - [`sequelize-fastify`](https://github.com/hsynlms/sequelize-fastify) A simple
554
574
  and lightweight Sequelize plugin for Fastify.
575
+ - [`typeorm-fastify-plugin`](https://github.com/jclemens24/fastify-typeorm) A simple
576
+ and updated Typeorm plugin for use with Fastify.
555
577
 
556
578
  #### [Community Tools](#community-tools)
557
579
  - [`fast-maker`](https://github.com/imjuni/fast-maker) route configuration
558
580
  generator by directory structure.
581
+ - [`simple-tjscli`](https://github.com/imjuni/simple-tjscli) CLI tool to
582
+ generate JSON Schema from TypeScript interfaces.
@@ -65,6 +65,35 @@ Starting from v4, all the `GET` routes will create a sibling `HEAD` route.
65
65
  You can revert this behaviour by setting the server's option `exposeHeadRoutes`
66
66
  to `false`.
67
67
 
68
+ ### Synchronous route definitions
69
+
70
+ The route registration has been made synchronous from v4.
71
+ This change was done to provide better error reporting for route definition.
72
+ As a result if you specify an `onRoute` hook in a plugin you should either:
73
+ * wrap your routes in a plugin (recommended)
74
+ * use `await register(...)`
75
+
76
+ For example refactor this:
77
+ ```
78
+ fastify.register((instance, opts, done) => {
79
+ instance.addHook('onRoute', (routeOptions) => {
80
+ const { path, method } = routeOptions;
81
+ console.log({ path, method });
82
+ });
83
+ done();
84
+ });
85
+ ```
86
+ Into this:
87
+ ```
88
+ await fastify.register((instance, opts, done) => {
89
+ instance.addHook('onRoute', (routeOptions) => {
90
+ const { path, method } = routeOptions;
91
+ console.log({ path, method });
92
+ });
93
+ done();
94
+ });
95
+ ```
96
+
68
97
  ## Non Breaking Changes
69
98
 
70
99
  ### Change of schema for multiple types
@@ -196,6 +196,11 @@ fastify.get('/html', (request, reply) => {
196
196
  reply.html({ hello: 'world' })
197
197
  })
198
198
  ```
199
+ Reminder that the `this` keyword is not available on *arrow functions*,
200
+ so when passing functions in *`decorateReply`* and *`decorateRequest`* as
201
+ a utility that also needs access to the `request` and `reply` instance,
202
+ a function that is defined using the `function` keyword is needed instead
203
+ of an *arrow function expression*.
199
204
 
200
205
  In the same way you can do this for the `request` object:
201
206
  ```js
@@ -2,9 +2,7 @@
2
2
 
3
3
  ## HTTP2
4
4
 
5
- _Fastify_ offers **experimental support** for HTTP2 starting from Node 8 LTS,
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`
@@ -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('onResponse', async (request, reply) => {
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
 
@@ -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) {