fastify 5.0.0 → 5.1.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 (138) hide show
  1. package/.borp.yaml +3 -0
  2. package/.vscode/settings.json +22 -0
  3. package/docs/Guides/Ecosystem.md +1 -8
  4. package/docs/Guides/Migration-Guide-V5.md +128 -4
  5. package/docs/Guides/Testing.md +51 -50
  6. package/docs/Guides/Write-Plugin.md +1 -1
  7. package/docs/Reference/ContentTypeParser.md +4 -4
  8. package/docs/Reference/Errors.md +1 -1
  9. package/docs/Reference/Reply.md +1 -5
  10. package/docs/Reference/Request.md +2 -1
  11. package/docs/Reference/Routes.md +9 -6
  12. package/docs/Reference/Server.md +1 -1
  13. package/fastify.d.ts +10 -1
  14. package/fastify.js +8 -6
  15. package/lib/contentTypeParser.js +9 -7
  16. package/lib/context.js +1 -2
  17. package/lib/fourOhFour.js +1 -1
  18. package/lib/{logger.js → logger-factory.js} +70 -122
  19. package/lib/logger-pino.js +68 -0
  20. package/lib/pluginOverride.js +1 -1
  21. package/lib/pluginUtils.js +2 -2
  22. package/lib/reply.js +4 -5
  23. package/lib/request.js +15 -9
  24. package/lib/route.js +23 -22
  25. package/lib/validation.js +2 -2
  26. package/package.json +12 -13
  27. package/test/404s.test.js +675 -629
  28. package/test/500s.test.js +72 -63
  29. package/test/allowUnsafeRegex.test.js +30 -26
  30. package/test/als.test.js +48 -45
  31. package/test/async-await.test.js +148 -134
  32. package/test/async-dispose.test.js +4 -4
  33. package/test/async_hooks.test.js +30 -28
  34. package/test/{bodyLimit.test.js → body-limit.test.js} +61 -58
  35. package/test/buffer.test.js +9 -10
  36. package/test/build/error-serializer.test.js +3 -4
  37. package/test/build/version.test.js +2 -3
  38. package/test/bundler/esbuild/bundler-test.js +10 -9
  39. package/test/bundler/webpack/bundler-test.js +10 -9
  40. package/test/case-insensitive.test.js +31 -28
  41. package/test/chainable.test.js +4 -5
  42. package/test/check.test.js +8 -9
  43. package/test/childLoggerFactory.test.js +56 -19
  44. package/test/client-timeout.test.js +5 -5
  45. package/test/close-pipelining.test.js +6 -7
  46. package/test/conditional-pino.test.js +47 -0
  47. package/test/connectionTimeout.test.js +10 -11
  48. package/test/constrained-routes.test.js +243 -236
  49. package/test/content-parser.test.js +17 -0
  50. package/test/custom-http-server.test.js +16 -20
  51. package/test/diagnostics-channel/404.test.js +15 -15
  52. package/test/diagnostics-channel/async-delay-request.test.js +25 -25
  53. package/test/diagnostics-channel/async-request.test.js +24 -24
  54. package/test/diagnostics-channel/error-before-handler.test.js +4 -5
  55. package/test/diagnostics-channel/error-request.test.js +19 -19
  56. package/test/diagnostics-channel/error-status.test.js +8 -8
  57. package/test/diagnostics-channel/init.test.js +6 -7
  58. package/test/diagnostics-channel/sync-delay-request.test.js +16 -16
  59. package/test/diagnostics-channel/sync-request-reply.test.js +16 -16
  60. package/test/diagnostics-channel/sync-request.test.js +19 -19
  61. package/test/esm/errorCodes.test.mjs +5 -5
  62. package/test/esm/esm.test.mjs +3 -3
  63. package/test/esm/named-exports.mjs +3 -3
  64. package/test/esm/other.mjs +2 -2
  65. package/test/hooks.test.js +6 -6
  66. package/test/http-methods/copy.test.js +22 -24
  67. package/test/http-methods/custom-http-methods.test.js +24 -21
  68. package/test/http-methods/get.test.js +97 -84
  69. package/test/http-methods/head.test.js +63 -54
  70. package/test/http-methods/lock.test.js +21 -20
  71. package/test/http-methods/mkcalendar.test.js +31 -27
  72. package/test/http-methods/mkcol.test.js +10 -10
  73. package/test/http-methods/move.test.js +11 -11
  74. package/test/http-methods/propfind.test.js +32 -27
  75. package/test/http-methods/proppatch.test.js +21 -19
  76. package/test/http-methods/report.test.js +32 -27
  77. package/test/http-methods/search.test.js +52 -47
  78. package/test/http-methods/trace.test.js +3 -4
  79. package/test/http-methods/unlock.test.js +10 -10
  80. package/test/http2/closing.test.js +50 -58
  81. package/test/http2/constraint.test.js +47 -50
  82. package/test/http2/head.test.js +18 -19
  83. package/test/http2/missing-http2-module.test.js +4 -5
  84. package/test/http2/plain.test.js +31 -31
  85. package/test/http2/secure-with-fallback.test.js +61 -61
  86. package/test/http2/secure.test.js +28 -31
  87. package/test/http2/unknown-http-method.test.js +13 -14
  88. package/test/https/custom-https-server.test.js +6 -7
  89. package/test/https/https.test.js +78 -78
  90. package/test/imports.test.js +5 -6
  91. package/test/internals/all.test.js +8 -11
  92. package/test/internals/contentTypeParser.test.js +5 -6
  93. package/test/internals/context.test.js +9 -11
  94. package/test/internals/decorator.test.js +20 -21
  95. package/test/internals/errors.test.js +427 -427
  96. package/test/internals/handleRequest.test.js +53 -42
  97. package/test/internals/hookRunner.test.js +99 -100
  98. package/test/internals/hooks.test.js +31 -35
  99. package/test/internals/initialConfig.test.js +92 -80
  100. package/test/internals/logger.test.js +28 -28
  101. package/test/internals/plugin.test.js +17 -18
  102. package/test/internals/reply-serialize.test.js +106 -106
  103. package/test/internals/reply.test.js +620 -585
  104. package/test/internals/reqIdGenFactory.test.js +31 -31
  105. package/test/internals/request-validate.test.js +218 -221
  106. package/test/internals/request.test.js +225 -107
  107. package/test/internals/server.test.js +15 -12
  108. package/test/internals/validation.test.js +35 -36
  109. package/test/{keepAliveTimeout.test.js → keep-alive-timeout.test.js} +9 -10
  110. package/test/noop-set.test.js +5 -5
  111. package/test/request-error.test.js +122 -0
  112. package/test/request-header-host.test.js +197 -0
  113. package/test/route.1.test.js +79 -72
  114. package/test/route.2.test.js +17 -16
  115. package/test/route.3.test.js +30 -26
  116. package/test/route.4.test.js +21 -25
  117. package/test/route.5.test.js +45 -64
  118. package/test/route.6.test.js +70 -89
  119. package/test/route.7.test.js +61 -65
  120. package/test/route.8.test.js +62 -0
  121. package/test/same-shape.test.js +5 -5
  122. package/test/serialize-response.test.js +9 -10
  123. package/test/server.test.js +67 -70
  124. package/test/test-reporter.mjs +68 -0
  125. package/test/types/fastify.test-d.ts +12 -0
  126. package/test/types/hooks.test-d.ts +2 -1
  127. package/test/types/instance.test-d.ts +10 -12
  128. package/test/types/plugin.test-d.ts +15 -7
  129. package/test/types/register.test-d.ts +20 -4
  130. package/test/types/route.test-d.ts +33 -3
  131. package/test/versioned-routes.test.js +126 -113
  132. package/test/web-api.test.js +48 -37
  133. package/test/wrapThenable.test.js +10 -9
  134. package/types/hooks.d.ts +1 -0
  135. package/types/register.d.ts +12 -3
  136. package/types/request.d.ts +2 -2
  137. package/types/utils.d.ts +10 -2
  138. package/test/types/import.js +0 -2
package/.borp.yaml ADDED
@@ -0,0 +1,3 @@
1
+ files:
2
+ - 'test/**/*.test.js'
3
+ - 'test/**/*.test.mjs'
@@ -0,0 +1,22 @@
1
+ {
2
+ "workbench.colorCustomizations": {
3
+ "[GitHub Dark]": {
4
+ "tab.activeBackground": "#0d0d0d",
5
+ "tab.activeBorder": "#ffff00"
6
+ },
7
+ "activityBar.background": "#FBE7B2",
8
+ "activityBar.foreground": "#52358C",
9
+ "activityBar.inactiveForeground": "#616161",
10
+ "activityBar.activeBorder": "#04184d",
11
+ "activityBar.activeBackground": "#C3B48B",
12
+ "activityBar.border": "#C3B48B",
13
+ "titleBar.activeBackground": "#D2BE88",
14
+ "titleBar.activeForeground": "#52358C",
15
+ "titleBar.inactiveBackground": "#bdb59c",
16
+ "titleBar.inactiveForeground": "#616161",
17
+ "titleBar.border": "#C3B48B",
18
+ "statusBar.background": "#E9DBB7",
19
+ "statusBar.foreground": "#52358C",
20
+ "statusBar.border": "#C3B48B"
21
+ }
22
+ }
@@ -12,8 +12,6 @@ section.
12
12
  [accepts](https://www.npmjs.com/package/accepts) in your request object.
13
13
  - [`@fastify/accepts-serializer`](https://github.com/fastify/fastify-accepts-serializer)
14
14
  to serialize to output according to the `Accept` header.
15
- - [`@fastify/any-schema`](https://github.com/fastify/any-schema-you-like) Save
16
- multiple schemas and decide which one to use to serialize the payload.
17
15
  - [`@fastify/auth`](https://github.com/fastify/fastify-auth) Run multiple auth
18
16
  functions in Fastify.
19
17
  - [`@fastify/autoload`](https://github.com/fastify/fastify-autoload) Require all
@@ -43,10 +41,7 @@ section.
43
41
  [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery) protection to
44
42
  Fastify.
45
43
  - [`@fastify/diagnostics-channel`](https://github.com/fastify/fastify-diagnostics-channel)
46
- Plugin to deal with `diagnostics_channel` on Fastify
47
- - [`@fastify/early-hints`](https://github.com/fastify/fastify-early-hints) Plugin
48
- to add HTTP 103 feature based on [RFC
49
- 8297](https://datatracker.ietf.org/doc/html/rfc8297).
44
+ Plugin to deal with `diagnostics_channel` on Fastify.
50
45
  - [`@fastify/elasticsearch`](https://github.com/fastify/fastify-elasticsearch)
51
46
  Plugin to share the same ES client.
52
47
  - [`@fastify/env`](https://github.com/fastify/fastify-env) Load and check
@@ -124,8 +119,6 @@ section.
124
119
  HTTP errors and assertions, but also more request and reply methods.
125
120
  - [`@fastify/session`](https://github.com/fastify/session) a session plugin for
126
121
  Fastify.
127
- - [`@fastify/soap-client`](https://github.com/fastify/fastify-soap-client) a SOAP
128
- client plugin for Fastify.
129
122
  - [`@fastify/static`](https://github.com/fastify/fastify-static) Plugin for
130
123
  serving static files as fast as possible.
131
124
  - [`@fastify/swagger`](https://github.com/fastify/fastify-swagger) Plugin for
@@ -432,16 +432,16 @@ We have removed the following HTTP methods from Fastify:
432
432
  - `TRACE`
433
433
  - `SEARCH`
434
434
 
435
- It's now possible to add them back using the `acceptHTTPMethod` method.
435
+ It's now possible to add them back using the `addHttpMethod` method.
436
436
 
437
437
  ```js
438
438
  const fastify = Fastify()
439
439
 
440
440
  // add a new http method on top of the default ones:
441
- fastify.acceptHTTPMethod('REBIND')
441
+ fastify.addHttpMethod('REBIND')
442
442
 
443
443
  // add a new HTTP method that accepts a body:
444
- fastify.acceptHTTPMethod('REBIND', { hasBody: true })
444
+ fastify.addHttpMethod('REBIND', { hasBody: true })
445
445
 
446
446
  // reads the HTTP methods list:
447
447
  fastify.supportedMethods // returns a string array
@@ -538,7 +538,7 @@ so you should have already updated your code.
538
538
 
539
539
  ### Diagnostic Channel support
540
540
 
541
- Fastify v5 now supports the [Diagnostic Channel](https://nodejs.org/api/diagnostic_channel.html)
541
+ Fastify v5 now supports the [Diagnostics Channel](https://nodejs.org/api/diagnostics_channel.html)
542
542
  API natively
543
543
  and provides a way to trace the lifecycle of a request.
544
544
 
@@ -586,3 +586,127 @@ fastify.listen({ port: 0 }, function () {
586
586
 
587
587
  See the [documentation](https://github.com/fastify/fastify/blob/main/docs/Reference/Hooks.md#diagnostics-channel-hooks)
588
588
  and [#5252](https://github.com/fastify/fastify/pull/5252) for additional details.
589
+
590
+ ## Contributors
591
+
592
+ The complete list of contributors, across all of the core
593
+ Fastify packages, is provided below. Please consider
594
+ contributing to those that are capable of accepting sponsorships.
595
+
596
+ | Contributor | Sponsor Link | Packages |
597
+ | --- | --- | --- |
598
+ | 10xLaCroixDrinker | [❤️ sponsor](https://github.com/sponsors/10xLaCroixDrinker) | fastify-cli |
599
+ | Bram-dc | | fastify; fastify-swagger |
600
+ | BrianValente | | fastify |
601
+ | BryanAbate | | fastify-cli |
602
+ | Cadienvan | [❤️ sponsor](https://github.com/sponsors/Cadienvan) | fastify |
603
+ | Cangit | | fastify |
604
+ | Cyberlane | | fastify-elasticsearch |
605
+ | Eomm | [❤️ sponsor](https://github.com/sponsors/Eomm) | ajv-compiler; fastify; fastify-awilix; fastify-diagnostics-channel; fastify-elasticsearch; fastify-hotwire; fastify-mongodb; fastify-nextjs; fastify-swagger-ui; under-pressure |
606
+ | EstebanDalelR | [❤️ sponsor](https://github.com/sponsors/EstebanDalelR) | fastify-cli |
607
+ | Fdawgs | [❤️ sponsor](https://github.com/sponsors/Fdawgs) | aws-lambda-fastify; csrf-protection; env-schema; fastify; fastify-accepts; fastify-accepts-serializer; fastify-auth; fastify-awilix; fastify-basic-auth; fastify-bearer-auth; fastify-caching; fastify-circuit-breaker; fastify-cli; fastify-cookie; fastify-cors; fastify-diagnostics-channel; fastify-elasticsearch; fastify-env; fastify-error; fastify-etag; fastify-express; fastify-flash; fastify-formbody; fastify-funky; fastify-helmet; fastify-hotwire; fastify-http-proxy; fastify-jwt; fastify-kafka; fastify-leveldb; fastify-mongodb; fastify-multipart; fastify-mysql; fastify-nextjs; fastify-oauth2; fastify-passport; fastify-plugin; fastify-postgres; fastify-rate-limit; fastify-redis; fastify-reply-from; fastify-request-context; fastify-response-validation; fastify-routes; fastify-routes-stats; fastify-schedule; fastify-secure-session; fastify-sensible; fastify-swagger-ui; fastify-url-data; fastify-websocket; fastify-zipkin; fluent-json-schema; forwarded; middie; point-of-view; process-warning; proxy-addr; safe-regex2; secure-json-parse; under-pressure |
608
+ | Gehbt | | fastify-secure-session |
609
+ | Gesma94 | | fastify-routes-stats |
610
+ | H4ad | [❤️ sponsor](https://github.com/sponsors/H4ad) | aws-lambda-fastify |
611
+ | JohanManders | | fastify-secure-session |
612
+ | LiviaMedeiros | | fastify |
613
+ | Momy93 | | fastify-secure-session |
614
+ | MunifTanjim | | fastify-swagger-ui |
615
+ | Nanosync | | fastify-secure-session |
616
+ | RafaelGSS | [❤️ sponsor](https://github.com/sponsors/RafaelGSS) | fastify; under-pressure |
617
+ | Rantoledo | | fastify |
618
+ | SMNBLMRR | | fastify |
619
+ | SimoneDevkt | | fastify-cli |
620
+ | Tony133 | | fastify |
621
+ | Uzlopak | [❤️ sponsor](https://github.com/sponsors/Uzlopak) | fastify; fastify-autoload; fastify-diagnostics-channel; fastify-hotwire; fastify-nextjs; fastify-passport; fastify-plugin; fastify-rate-limit; fastify-routes; fastify-static; fastify-swagger-ui; point-of-view; under-pressure |
622
+ | Zamiell | | fastify-secure-session |
623
+ | aadito123 | | fastify |
624
+ | aaroncadillac | [❤️ sponsor](https://github.com/sponsors/aaroncadillac) | fastify |
625
+ | aarontravass | | fastify |
626
+ | acro5piano | [❤️ sponsor](https://github.com/sponsors/acro5piano) | fastify-secure-session |
627
+ | adamward459 | | fastify-cli |
628
+ | adrai | [❤️ sponsor](https://github.com/sponsors/adrai) | aws-lambda-fastify |
629
+ | alenap93 | | fastify |
630
+ | alexandrucancescu | | fastify-nextjs |
631
+ | anthonyringoet | | aws-lambda-fastify |
632
+ | arshcodemod | | fastify |
633
+ | autopulated | | point-of-view |
634
+ | barbieri | | fastify |
635
+ | beyazit | | fastify |
636
+ | big-kahuna-burger | [❤️ sponsor](https://github.com/sponsors/big-kahuna-burger) | fastify-cli; fastify-compress; fastify-helmet |
637
+ | bilalshareef | | fastify-routes |
638
+ | blue86321 | | fastify-swagger-ui |
639
+ | bodinsamuel | | fastify-rate-limit |
640
+ | busybox11 | [❤️ sponsor](https://github.com/sponsors/busybox11) | fastify |
641
+ | climba03003 | | csrf-protection; fastify; fastify-accepts; fastify-accepts-serializer; fastify-auth; fastify-basic-auth; fastify-bearer-auth; fastify-caching; fastify-circuit-breaker; fastify-compress; fastify-cors; fastify-env; fastify-etag; fastify-flash; fastify-formbody; fastify-http-proxy; fastify-mongodb; fastify-swagger-ui; fastify-url-data; fastify-websocket; middie |
642
+ | dancastillo | [❤️ sponsor](https://github.com/sponsors/dancastillo) | fastify; fastify-basic-auth; fastify-caching; fastify-circuit-breaker; fastify-cors; fastify-helmet; fastify-passport; fastify-response-validation; fastify-routes; fastify-schedule |
643
+ | danny-andrews | | fastify-kafka |
644
+ | davidcralph | [❤️ sponsor](https://github.com/sponsors/davidcralph) | csrf-protection |
645
+ | davideroffo | | under-pressure |
646
+ | dhensby | | fastify-cli |
647
+ | dmkng | | fastify |
648
+ | domdomegg | | fastify |
649
+ | faustman | | fastify-cli |
650
+ | floridemai | | fluent-json-schema |
651
+ | fox1t | | fastify-autoload |
652
+ | giuliowaitforitdavide | | fastify |
653
+ | gunters63 | | fastify-reply-from |
654
+ | gurgunday | | fastify; fastify-circuit-breaker; fastify-cookie; fastify-multipart; fastify-mysql; fastify-rate-limit; fastify-response-validation; fastify-sensible; fastify-swagger-ui; fluent-json-schema; middie; proxy-addr; safe-regex2; secure-json-parse |
655
+ | ildella | | under-pressure |
656
+ | james-kaguru | | fastify |
657
+ | jcbain | | fastify-http-proxy |
658
+ | jdhollander | | fastify-swagger-ui |
659
+ | jean-michelet | | fastify; fastify-autoload; fastify-cli; fastify-mysql; fastify-sensible |
660
+ | johaven | | fastify-multipart |
661
+ | jordanebelanger | | fastify-plugin |
662
+ | jscheffner | | fastify |
663
+ | jsprw | | fastify-secure-session |
664
+ | jsumners | [❤️ sponsor](https://github.com/sponsors/jsumners) | ajv-compiler; avvio; csrf-protection; env-schema; fast-json-stringify; fastify; fastify-accepts; fastify-accepts-serializer; fastify-auth; fastify-autoload; fastify-awilix; fastify-basic-auth; fastify-bearer-auth; fastify-caching; fastify-circuit-breaker; fastify-compress; fastify-cookie; fastify-cors; fastify-env; fastify-error; fastify-etag; fastify-express; fastify-flash; fastify-formbody; fastify-funky; fastify-helmet; fastify-http-proxy; fastify-jwt; fastify-kafka; fastify-leveldb; fastify-multipart; fastify-mysql; fastify-oauth2; fastify-plugin; fastify-postgres; fastify-redis; fastify-reply-from; fastify-request-context; fastify-response-validation; fastify-routes; fastify-routes-stats; fastify-schedule; fastify-secure-session; fastify-sensible; fastify-static; fastify-swagger; fastify-swagger-ui; fastify-url-data; fastify-websocket; fastify-zipkin; fluent-json-schema; forwarded; light-my-request; middie; process-warning; proxy-addr; safe-regex2; secure-json-parse; under-pressure |
665
+ | karankraina | | under-pressure |
666
+ | kerolloz | [❤️ sponsor](https://github.com/sponsors/kerolloz) | fastify-jwt |
667
+ | kibertoad | | fastify-rate-limit |
668
+ | kukidon-dev | | fastify-passport |
669
+ | kunal097 | | fastify |
670
+ | lamweili | | fastify-sensible |
671
+ | lemonclown | | fastify-mongodb |
672
+ | liuhanqu | | fastify |
673
+ | matthyk | | fastify-plugin |
674
+ | mch-dsk | | fastify |
675
+ | mcollina | [❤️ sponsor](https://github.com/sponsors/mcollina) | ajv-compiler; avvio; csrf-protection; fastify; fastify-accepts; fastify-accepts-serializer; fastify-auth; fastify-autoload; fastify-awilix; fastify-basic-auth; fastify-bearer-auth; fastify-caching; fastify-circuit-breaker; fastify-cli; fastify-compress; fastify-cookie; fastify-cors; fastify-diagnostics-channel; fastify-elasticsearch; fastify-env; fastify-etag; fastify-express; fastify-flash; fastify-formbody; fastify-funky; fastify-helmet; fastify-http-proxy; fastify-jwt; fastify-kafka; fastify-leveldb; fastify-multipart; fastify-mysql; fastify-oauth2; fastify-passport; fastify-plugin; fastify-postgres; fastify-rate-limit; fastify-redis; fastify-reply-from; fastify-request-context; fastify-response-validation; fastify-routes; fastify-routes-stats; fastify-schedule; fastify-secure-session; fastify-static; fastify-swagger; fastify-swagger-ui; fastify-url-data; fastify-websocket; fastify-zipkin; fluent-json-schema; light-my-request; middie; point-of-view; proxy-addr; secure-json-parse; under-pressure |
676
+ | melroy89 | [❤️ sponsor](https://github.com/sponsors/melroy89) | under-pressure |
677
+ | metcoder95 | [❤️ sponsor](https://github.com/sponsors/metcoder95) | fastify-elasticsearch |
678
+ | mhamann | | fastify-cli |
679
+ | mihaur | | fastify-elasticsearch |
680
+ | mikesamm | | fastify |
681
+ | mikhael-abdallah | | secure-json-parse |
682
+ | miquelfire | [❤️ sponsor](https://github.com/sponsors/miquelfire) | fastify-routes |
683
+ | miraries | | fastify-swagger-ui |
684
+ | mohab-sameh | | fastify |
685
+ | monish001 | | fastify |
686
+ | moradebianchetti81 | | fastify |
687
+ | mouhannad-sh | | aws-lambda-fastify |
688
+ | multivoltage | | point-of-view |
689
+ | muya | [❤️ sponsor](https://github.com/sponsors/muya) | under-pressure |
690
+ | mweberxyz | | point-of-view |
691
+ | nflaig | | fastify |
692
+ | nickfla1 | | avvio |
693
+ | o-az | | process-warning |
694
+ | ojeytonwilliams | | csrf-protection |
695
+ | onosendi | | fastify-formbody |
696
+ | philippviereck | | fastify |
697
+ | pip77 | | fastify-mongodb |
698
+ | puskin94 | | fastify |
699
+ | remidewitte | | fastify |
700
+ | rozzilla | | fastify |
701
+ | samialdury | | fastify-cli |
702
+ | sknetl | | fastify-cors |
703
+ | sourcecodeit | | fastify |
704
+ | synapse | | env-schema |
705
+ | timursaurus | | secure-json-parse |
706
+ | tlhunter | | fastify |
707
+ | tlund101 | | fastify-rate-limit |
708
+ | ttshivers | | fastify-http-proxy |
709
+ | voxpelli | [❤️ sponsor](https://github.com/sponsors/voxpelli) | fastify |
710
+ | weixinwu | | fastify-cli |
711
+ | zetaraku | | fastify-cli |
712
+
@@ -5,15 +5,15 @@
5
5
 
6
6
  Testing is one of the most important parts of developing an application. Fastify
7
7
  is very flexible when it comes to testing and is compatible with most testing
8
- frameworks (such as [Tap](https://www.npmjs.com/package/tap), which is used in
9
- the examples below).
8
+ frameworks (such as [Node Test Runner](https://nodejs.org/api/test.html),
9
+ which is used in the examples below).
10
10
 
11
11
  ## Application
12
12
 
13
13
  Let's `cd` into a fresh directory called 'testing-example' and type `npm init
14
14
  -y` in our terminal.
15
15
 
16
- Run `npm i fastify && npm i tap pino-pretty -D`
16
+ Run `npm i fastify && npm i pino-pretty -D`
17
17
 
18
18
  ### Separating concerns makes testing easy
19
19
 
@@ -113,24 +113,25 @@ Now we can replace our `console.log` calls with actual tests!
113
113
 
114
114
  In your `package.json` change the "test" script to:
115
115
 
116
- `"test": "tap --reporter=list --watch"`
116
+ `"test": "node --test --watch"`
117
117
 
118
118
  **app.test.js**:
119
119
 
120
120
  ```js
121
121
  'use strict'
122
122
 
123
- const { test } = require('tap')
123
+ const { test } = require('node:test')
124
124
  const build = require('./app')
125
125
 
126
126
  test('requests the "/" route', async t => {
127
+ t.plan(1)
127
128
  const app = build()
128
129
 
129
130
  const response = await app.inject({
130
131
  method: 'GET',
131
132
  url: '/'
132
133
  })
133
- t.equal(response.statusCode, 200, 'returns a status code of 200')
134
+ t.assert.strictEqual(response.statusCode, 200, 'returns a status code of 200')
134
135
  })
135
136
  ```
136
137
 
@@ -214,26 +215,26 @@ module.exports = buildFastify
214
215
 
215
216
  **test.js**
216
217
  ```js
217
- const tap = require('tap')
218
+ const { test } = require('node:test')
218
219
  const buildFastify = require('./app')
219
220
 
220
- tap.test('GET `/` route', t => {
221
+ test('GET `/` route', t => {
221
222
  t.plan(4)
222
223
 
223
224
  const fastify = buildFastify()
224
225
 
225
226
  // At the end of your tests it is highly recommended to call `.close()`
226
227
  // to ensure that all connections to external services get closed.
227
- t.teardown(() => fastify.close())
228
+ t.after(() => fastify.close())
228
229
 
229
230
  fastify.inject({
230
231
  method: 'GET',
231
232
  url: '/'
232
233
  }, (err, response) => {
233
- t.error(err)
234
- t.equal(response.statusCode, 200)
235
- t.equal(response.headers['content-type'], 'application/json; charset=utf-8')
236
- t.same(response.json(), { hello: 'world' })
234
+ t.assert.ifError(err)
235
+ t.assert.strictEqual(response.statusCode, 200)
236
+ t.assert.strictEqual(response.headers['content-type'], 'application/json; charset=utf-8')
237
+ t.assert.deepStrictEqual(response.json(), { hello: 'world' })
237
238
  })
238
239
  })
239
240
  ```
@@ -248,11 +249,11 @@ Uses **app.js** from the previous example.
248
249
 
249
250
  **test-listen.js** (testing with [`undici`](https://www.npmjs.com/package/undici))
250
251
  ```js
251
- const tap = require('tap')
252
+ const { test } = require('node:test')
252
253
  const { Client } = require('undici')
253
254
  const buildFastify = require('./app')
254
255
 
255
- tap.test('should work with undici', async t => {
256
+ test('should work with undici', async t => {
256
257
  t.plan(2)
257
258
 
258
259
  const fastify = buildFastify()
@@ -266,15 +267,15 @@ tap.test('should work with undici', async t => {
266
267
  }
267
268
  )
268
269
 
269
- t.teardown(() => {
270
+ t.after(() => {
270
271
  fastify.close()
271
272
  client.close()
272
273
  })
273
274
 
274
275
  const response = await client.request({ method: 'GET', path: '/' })
275
276
 
276
- t.equal(await response.body.text(), '{"hello":"world"}')
277
- t.equal(response.statusCode, 200)
277
+ t.assert.strictEqual(await response.body.text(), '{"hello":"world"}')
278
+ t.assert.strictEqual(response.statusCode, 200)
278
279
  })
279
280
  ```
280
281
 
@@ -284,15 +285,15 @@ may be used without requiring any extra dependencies:
284
285
 
285
286
  **test-listen.js**
286
287
  ```js
287
- const tap = require('tap')
288
+ const { test } = require('node:test')
288
289
  const buildFastify = require('./app')
289
290
 
290
- tap.test('should work with fetch', async t => {
291
+ test('should work with fetch', async t => {
291
292
  t.plan(3)
292
293
 
293
294
  const fastify = buildFastify()
294
295
 
295
- t.teardown(() => fastify.close())
296
+ t.after(() => fastify.close())
296
297
 
297
298
  await fastify.listen()
298
299
 
@@ -300,26 +301,27 @@ tap.test('should work with fetch', async t => {
300
301
  'http://localhost:' + fastify.server.address().port
301
302
  )
302
303
 
303
- t.equal(response.status, 200)
304
- t.equal(
304
+ t.assert.strictEqual(response.status, 200)
305
+ t.assert.strictEqual(
305
306
  response.headers.get('content-type'),
306
307
  'application/json; charset=utf-8'
307
308
  )
308
- t.has(await response.json(), { hello: 'world' })
309
+ const jsonResult = await response.json()
310
+ t.assert.strictEqual(jsonResult.hello, 'world')
309
311
  })
310
312
  ```
311
313
 
312
314
  **test-ready.js** (testing with
313
315
  [`SuperTest`](https://www.npmjs.com/package/supertest))
314
316
  ```js
315
- const tap = require('tap')
317
+ const { test } = require('node:test')
316
318
  const supertest = require('supertest')
317
319
  const buildFastify = require('./app')
318
320
 
319
- tap.test('GET `/` route', async (t) => {
321
+ test('GET `/` route', async (t) => {
320
322
  const fastify = buildFastify()
321
323
 
322
- t.teardown(() => fastify.close())
324
+ t.after(() => fastify.close())
323
325
 
324
326
  await fastify.ready()
325
327
 
@@ -327,21 +329,20 @@ tap.test('GET `/` route', async (t) => {
327
329
  .get('/')
328
330
  .expect(200)
329
331
  .expect('Content-Type', 'application/json; charset=utf-8')
330
- t.same(response.body, { hello: 'world' })
332
+ t.assert.deepStrictEqual(response.body, { hello: 'world' })
331
333
  })
332
334
  ```
333
335
 
334
- ### How to inspect tap tests
336
+ ### How to inspect node tests
335
337
  1. Isolate your test by passing the `{only: true}` option
336
338
  ```javascript
337
339
  test('should ...', {only: true}, t => ...)
338
340
  ```
339
- 2. Run `tap` using `npx`
341
+ 2. Run `node --test`
340
342
  ```bash
341
- > npx tap -O -T --node-arg=--inspect-brk test/<test-file.test.js>
343
+ > node --test --test-only --node-arg=--inspect-brk test/<test-file.test.js>
342
344
  ```
343
- - `-O` specifies to run tests with the `only` option enabled
344
- - `-T` specifies not to timeout (while you're debugging)
345
+ - `--test-only` specifies to run tests with the `only` option enabled
345
346
  - `--node-arg=--inspect-brk` will launch the node debugger
346
347
  3. In VS Code, create and launch a `Node.js: Attach` debug configuration. No
347
348
  modification should be necessary.
@@ -355,7 +356,7 @@ Now you should be able to step through your test file (and the rest of
355
356
  Let's `cd` into a fresh directory called 'testing-plugin-example' and type `npm init
356
357
  -y` in our terminal.
357
358
 
358
- Run `npm i fastify fastify-plugin && npm i tap -D`
359
+ Run `npm i fastify fastify-plugin`
359
360
 
360
361
  **plugin/myFirstPlugin.js**:
361
362
 
@@ -376,10 +377,10 @@ A basic example of a Plugin. See [Plugin Guide](./Plugins-Guide.md)
376
377
 
377
378
  ```js
378
379
  const Fastify = require("fastify");
379
- const tap = require("tap");
380
+ const { test } = require("node:test");
380
381
  const myPlugin = require("../plugin/myFirstPlugin");
381
382
 
382
- tap.test("Test the Plugin Route", async t => {
383
+ test("Test the Plugin Route", async t => {
383
384
  // Create a mock fastify application to test the plugin
384
385
  const fastify = Fastify()
385
386
 
@@ -412,18 +413,18 @@ Now we can replace our `console.log` calls with actual tests!
412
413
 
413
414
  In your `package.json` change the "test" script to:
414
415
 
415
- `"test": "tap --reporter=list --watch"`
416
+ `"test": "node --test --watch"`
416
417
 
417
- Create the tap test for the endpoint.
418
+ Create the test for the endpoint.
418
419
 
419
420
  **test/myFirstPlugin.test.js**:
420
421
 
421
422
  ```js
422
423
  const Fastify = require("fastify");
423
- const tap = require("tap");
424
+ const { test } = require("node:test");
424
425
  const myPlugin = require("../plugin/myFirstPlugin");
425
426
 
426
- tap.test("Test the Plugin Route", async t => {
427
+ test("Test the Plugin Route", async t => {
427
428
  // Specifies the number of test
428
429
  t.plan(2)
429
430
 
@@ -440,8 +441,8 @@ tap.test("Test the Plugin Route", async t => {
440
441
  url: "/"
441
442
  })
442
443
 
443
- t.equal(fastifyResponse.statusCode, 200)
444
- t.same(JSON.parse(fastifyResponse.body), { message: "Hello World" })
444
+ t.assert.strictEqual(fastifyResponse.statusCode, 200)
445
+ t.assert.deepStrictEqual(JSON.parse(fastifyResponse.body), { message: "Hello World" })
445
446
  })
446
447
  ```
447
448
 
@@ -453,10 +454,10 @@ Test the ```.decorate()``` and ```.decorateRequest()```.
453
454
 
454
455
  ```js
455
456
  const Fastify = require("fastify");
456
- const tap = require("tap");
457
+ const { test }= require("node:test");
457
458
  const myPlugin = require("../plugin/myFirstPlugin");
458
459
 
459
- tap.test("Test the Plugin Route", async t => {
460
+ test("Test the Plugin Route", async t => {
460
461
  t.plan(5)
461
462
  const fastify = Fastify()
462
463
 
@@ -464,9 +465,9 @@ tap.test("Test the Plugin Route", async t => {
464
465
 
465
466
  fastify.get("/", async (request, reply) => {
466
467
  // Testing the fastify decorators
467
- t.not(request.helloRequest, null)
468
- t.ok(request.helloRequest, "Hello World")
469
- t.ok(fastify.helloInstance, "Hello Fastify Instance")
468
+ t.assert.ifError(request.helloRequest)
469
+ t.assert.ok(request.helloRequest, "Hello World")
470
+ t.assert.ok(fastify.helloInstance, "Hello Fastify Instance")
470
471
  return ({ message: request.helloRequest })
471
472
  })
472
473
 
@@ -474,7 +475,7 @@ tap.test("Test the Plugin Route", async t => {
474
475
  method: "GET",
475
476
  url: "/"
476
477
  })
477
- t.equal(fastifyResponse.statusCode, 200)
478
- t.same(JSON.parse(fastifyResponse.body), { message: "Hello World" })
478
+ t.assert.strictEqual(fastifyResponse.statusCode, 200)
479
+ t.assert.deepStrictEqual(JSON.parse(fastifyResponse.body), { message: "Hello World" })
479
480
  })
480
- ```
481
+ ```
@@ -60,7 +60,7 @@ A plugin without tests will not be accepted to the ecosystem list. A lack of
60
60
  tests does not inspire trust nor guarantee that the code will continue to work
61
61
  among different versions of its dependencies.
62
62
 
63
- We do not enforce any testing library. We use [`tap`](https://www.node-tap.org/)
63
+ We do not enforce any testing library. We use [`node:test`](https://nodejs.org/api/test.html)
64
64
  since it offers out-of-the-box parallel testing and code coverage, but it is up
65
65
  to you to choose your library of preference.
66
66
  We highly recommend you read the [Plugin Testing](./Testing.md#plugins) to
@@ -53,7 +53,7 @@ fastify.addContentTypeParser(['text/xml', 'application/xml'], function (request,
53
53
 
54
54
  // Async is also supported in Node versions >= 8.0.0
55
55
  fastify.addContentTypeParser('application/jsoff', async function (request, payload) {
56
- var res = await jsoffParserAsync(payload)
56
+ const res = await jsoffParserAsync(payload)
57
57
 
58
58
  return res
59
59
  })
@@ -181,7 +181,7 @@ limit is exceeded the custom parser will not be invoked.
181
181
  ```js
182
182
  fastify.addContentTypeParser('application/json', { parseAs: 'string' }, function (req, body, done) {
183
183
  try {
184
- var json = JSON.parse(body)
184
+ const json = JSON.parse(body)
185
185
  done(null, json)
186
186
  } catch (err) {
187
187
  err.statusCode = 400
@@ -206,7 +206,7 @@ There are some cases where you need to catch all requests regardless of their
206
206
  content type. With Fastify, you can just use the `'*'` content type.
207
207
  ```js
208
208
  fastify.addContentTypeParser('*', function (request, payload, done) {
209
- var data = ''
209
+ let data = ''
210
210
  payload.on('data', chunk => { data += chunk })
211
211
  payload.on('end', () => {
212
212
  done(null, data)
@@ -266,7 +266,7 @@ only on those that don't have a specific one, you should call the
266
266
  fastify.removeAllContentTypeParsers()
267
267
 
268
268
  fastify.addContentTypeParser('*', function (request, payload, done) {
269
- var data = ''
269
+ const data = ''
270
270
  payload.on('data', chunk => { data += chunk })
271
271
  payload.on('end', () => {
272
272
  done(null, data)
@@ -5,7 +5,7 @@
5
5
 
6
6
  **Table of contents**
7
7
  - [Errors](#errors)
8
- - [Error Handling In Node.js](#error-handling-in-node.js)
8
+ - [Error Handling In Node.js](#error-handling-in-nodejs)
9
9
  - [Uncaught Errors](#uncaught-errors)
10
10
  - [Catching Errors In Promises](#catching-errors-in-promises)
11
11
  - [Errors In Fastify](#errors-in-fastify)
@@ -19,7 +19,6 @@
19
19
  - [.removeTrailer(key)](#removetrailerkey)
20
20
  - [.redirect(dest, [code ,])](#redirectdest--code)
21
21
  - [.callNotFound()](#callnotfound)
22
- - [.getResponseTime()](#getresponsetime)
23
22
  - [.type(contentType)](#typecontenttype)
24
23
  - [.getSerializationFunction(schema | httpStatus, [contentType])](#getserializationfunctionschema--httpstatus)
25
24
  - [.compileSerializationSchema(schema, [httpStatus], [contentType])](#compileserializationschemaschema-httpstatus)
@@ -114,9 +113,6 @@ If not set via `reply.code`, the resulting `statusCode` will be `200`.
114
113
  Invokes the custom response time getter to calculate the amount of time passed
115
114
  since the request was received by Fastify.
116
115
 
117
- Note that unless this function is called in the [`onResponse`
118
- hook](./Hooks.md#onresponse) it will always return `0`.
119
-
120
116
  ```js
121
117
  const milliseconds = reply.elapsedTime
122
118
  ```
@@ -880,7 +876,7 @@ API:
880
876
  ```js
881
877
  fastify.setErrorHandler(function (error, request, reply) {
882
878
  request.log.warn(error)
883
- var statusCode = error.statusCode >= 400 ? error.statusCode : 500
879
+ const statusCode = error.statusCode >= 400 ? error.statusCode : 500
884
880
  reply
885
881
  .code(statusCode)
886
882
  .type('text/plain')
@@ -23,7 +23,8 @@ Request is a core Fastify object containing the following fields:
23
23
  - `host` - the host of the incoming request (derived from `X-Forwarded-Host`
24
24
  header when the [`trustProxy`](./Server.md#factory-trust-proxy) option is
25
25
  enabled). For HTTP/2 compatibility it returns `:authority` if no host header
26
- exists.
26
+ exists. When you use `requireHostHeader = false` in the server options, it
27
+ will fallback as empty when the host header is missing.
27
28
  - `hostname` - the host of the incoming request without the port
28
29
  - `port` - the port that the server is listening on
29
30
  - `protocol` - the protocol of the incoming request (`https` or `http`)
@@ -151,8 +151,11 @@ fastify.route({
151
151
  url: '/',
152
152
  schema: {
153
153
  querystring: {
154
- name: { type: 'string' },
155
- excitement: { type: 'integer' }
154
+ type: 'object',
155
+ properties: {
156
+ name: { type: 'string' },
157
+ excitement: { type: 'integer' }
158
+ }
156
159
  },
157
160
  response: {
158
161
  200: {
@@ -331,8 +334,8 @@ fastify.post('/name::verb') // will be interpreted as /name:verb
331
334
  Are you an `async/await` user? We have you covered!
332
335
  ```js
333
336
  fastify.get('/', options, async function (request, reply) {
334
- var data = await getData()
335
- var processed = await processData(data)
337
+ const data = await getData()
338
+ const processed = await processData(data)
336
339
  return processed
337
340
  })
338
341
  ```
@@ -346,8 +349,8 @@ handler or you will introduce a race condition in certain situations.
346
349
 
347
350
  ```js
348
351
  fastify.get('/', options, async function (request, reply) {
349
- var data = await getData()
350
- var processed = await processData(data)
352
+ const data = await getData()
353
+ const processed = await processData(data)
351
354
  return reply.send(processed)
352
355
  })
353
356
  ```
@@ -1559,7 +1559,7 @@ is set. It can be accessed using `fastify.errorHandler` and it logs the error
1559
1559
  with respect to its `statusCode`.
1560
1560
 
1561
1561
  ```js
1562
- var statusCode = error.statusCode
1562
+ const statusCode = error.statusCode
1563
1563
  if (statusCode >= 500) {
1564
1564
  log.error(error)
1565
1565
  } else if (statusCode >= 400) {