fastify 3.24.0 → 3.25.2
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/README.md +30 -29
- package/docs/{Benchmarking.md → Guides/Benchmarking.md} +14 -5
- package/docs/Guides/Ecosystem.md +513 -0
- package/docs/{Fluent-Schema.md → Guides/Fluent-Schema.md} +16 -7
- package/docs/{Getting-Started.md → Guides/Getting-Started.md} +180 -60
- package/docs/Guides/Index.md +30 -4
- package/docs/{Migration-Guide-V3.md → Guides/Migration-Guide-V3.md} +43 -37
- package/docs/{Plugins-Guide.md → Guides/Plugins-Guide.md} +196 -82
- package/docs/{Recommendations.md → Guides/Recommendations.md} +17 -10
- package/docs/{Serverless.md → Guides/Serverless.md} +200 -42
- package/docs/Guides/Style-Guide.md +246 -0
- package/docs/{Testing.md → Guides/Testing.md} +26 -12
- package/docs/Guides/Write-Plugin.md +102 -0
- package/docs/{ContentTypeParser.md → Reference/ContentTypeParser.md} +68 -30
- package/docs/{Decorators.md → Reference/Decorators.md} +52 -47
- package/docs/{Encapsulation.md → Reference/Encapsulation.md} +3 -3
- package/docs/{Errors.md → Reference/Errors.md} +77 -47
- package/docs/{HTTP2.md → Reference/HTTP2.md} +13 -13
- package/docs/{Hooks.md → Reference/Hooks.md} +157 -70
- package/docs/Reference/Index.md +71 -0
- package/docs/{LTS.md → Reference/LTS.md} +31 -32
- package/docs/{Lifecycle.md → Reference/Lifecycle.md} +15 -7
- package/docs/{Logging.md → Reference/Logging.md} +68 -28
- package/docs/Reference/Middleware.md +78 -0
- package/docs/{Plugins.md → Reference/Plugins.md} +91 -34
- package/docs/{Reply.md → Reference/Reply.md} +205 -94
- package/docs/{Request.md → Reference/Request.md} +32 -16
- package/docs/{Routes.md → Reference/Routes.md} +243 -113
- package/docs/{Server.md → Reference/Server.md} +516 -267
- package/docs/{TypeScript.md → Reference/TypeScript.md} +451 -191
- package/docs/{Validation-and-Serialization.md → Reference/Validation-and-Serialization.md} +178 -86
- package/docs/index.md +24 -0
- package/examples/typescript-server.ts +1 -1
- package/fastify.js +2 -3
- package/lib/contentTypeParser.js +11 -6
- package/lib/decorate.js +6 -3
- package/lib/logger.js +1 -1
- package/lib/route.js +1 -1
- package/lib/server.js +9 -8
- package/package.json +9 -4
- package/test/als.test.js +74 -0
- package/test/constrained-routes.test.js +220 -0
- package/test/custom-parser.test.js +11 -2
- package/test/decorator.test.js +38 -0
- package/test/handler-context.test.js +11 -4
- package/test/http2/closing.test.js +14 -5
- package/test/http2/constraint.test.js +91 -0
- package/test/listen.test.js +36 -22
- package/test/logger.test.js +16 -0
- package/test/maxRequestsPerSocket.test.js +10 -0
- package/test/request-error.test.js +2 -8
- package/test/requestTimeout.test.js +4 -1
- package/test/router-options.test.js +10 -1
- package/test/schema-feature.test.js +146 -0
- package/test/stream.test.js +14 -3
- package/test/trust-proxy.test.js +15 -7
- package/test/types/instance.test-d.ts +52 -1
- package/test/types/request.test-d.ts +7 -1
- package/test/types/route.test-d.ts +21 -0
- package/types/hooks.d.ts +12 -1
- package/types/instance.d.ts +16 -6
- package/types/request.d.ts +4 -1
- package/types/route.d.ts +1 -1
- package/docs/Ecosystem.md +0 -211
- package/docs/Middleware.md +0 -53
- package/docs/Style-Guide.md +0 -185
- package/docs/Write-Plugin.md +0 -58
|
@@ -2,25 +2,40 @@
|
|
|
2
2
|
|
|
3
3
|
## TypeScript
|
|
4
4
|
|
|
5
|
-
The Fastify framework is written in vanilla JavaScript, and as such type
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
The Fastify framework is written in vanilla JavaScript, and as such type
|
|
6
|
+
definitions are not as easy to maintain; however, since version 2 and beyond,
|
|
7
|
+
maintainers and contributors have put in a great effort to improve the types.
|
|
8
|
+
|
|
9
|
+
The type system was changed in Fastify version 3. The new type system introduces
|
|
10
|
+
generic constraining and defaulting, plus a new way to define schema types such
|
|
11
|
+
as a request body, querystring, and more! As the team works on improving
|
|
12
|
+
framework and type definition synergy, sometimes parts of the API will not be
|
|
13
|
+
typed or may be typed incorrectly. We encourage you to **contribute** to help us
|
|
14
|
+
fill in the gaps. Just make sure to read our
|
|
15
|
+
[`CONTRIBUTING.md`](https://github.com/fastify/fastify/blob/main/CONTRIBUTING.md)
|
|
16
|
+
file before getting started to make sure things go smoothly!
|
|
8
17
|
|
|
9
18
|
> The documentation in this section covers Fastify version 3.x typings
|
|
10
19
|
|
|
11
|
-
> Plugins may or may not include typings. See [Plugins](#plugins) for more
|
|
20
|
+
> Plugins may or may not include typings. See [Plugins](#plugins) for more
|
|
21
|
+
> information. We encourage users to send pull requests to improve typings
|
|
22
|
+
> support.
|
|
12
23
|
|
|
13
24
|
🚨 Don't forget to install `@types/node`
|
|
14
25
|
|
|
15
26
|
## Learn By Example
|
|
16
27
|
|
|
17
|
-
The best way to learn the Fastify type system is by example! The following four
|
|
28
|
+
The best way to learn the Fastify type system is by example! The following four
|
|
29
|
+
examples should cover the most common Fastify development cases. After the
|
|
30
|
+
examples there is further, more detailed documentation for the type system.
|
|
18
31
|
|
|
19
32
|
### Getting Started
|
|
20
33
|
|
|
21
|
-
This example will get you up and running with Fastify and TypeScript. It results
|
|
34
|
+
This example will get you up and running with Fastify and TypeScript. It results
|
|
35
|
+
in a blank http Fastify server.
|
|
22
36
|
|
|
23
|
-
1. Create a new npm project, install Fastify, and install typescript & node.js
|
|
37
|
+
1. Create a new npm project, install Fastify, and install typescript & node.js
|
|
38
|
+
types as peer dependencies:
|
|
24
39
|
```bash
|
|
25
40
|
npm init -y
|
|
26
41
|
npm i fastify
|
|
@@ -36,13 +51,15 @@ This example will get you up and running with Fastify and TypeScript. It results
|
|
|
36
51
|
}
|
|
37
52
|
```
|
|
38
53
|
|
|
39
|
-
*Note: Set `target` property in `tsconfig.json` to `es2017` or greater to avoid [FastifyDeprecation](https://github.com/fastify/fastify/issues/3284) warning.*
|
|
40
|
-
|
|
41
54
|
3. Initialize a TypeScript configuration file:
|
|
42
55
|
```bash
|
|
43
56
|
npx tsc --init
|
|
44
57
|
```
|
|
45
|
-
or use one of the [recommended
|
|
58
|
+
or use one of the [recommended
|
|
59
|
+
ones](https://github.com/tsconfig/bases#node-10-tsconfigjson).
|
|
60
|
+
|
|
61
|
+
*Note: Set `target` property in `tsconfig.json` to `es2017` or greater to avoid
|
|
62
|
+
[FastifyDeprecation](https://github.com/fastify/fastify/issues/3284) warning.*
|
|
46
63
|
|
|
47
64
|
4. Create an `index.ts` file - this will contain the server code
|
|
48
65
|
5. Add the following code block to your file:
|
|
@@ -63,18 +80,30 @@ This example will get you up and running with Fastify and TypeScript. It results
|
|
|
63
80
|
console.log(`Server listening at ${address}`)
|
|
64
81
|
})
|
|
65
82
|
```
|
|
66
|
-
6. Run `npm run build` - this will compile `index.ts` into `index.js` which can
|
|
83
|
+
6. Run `npm run build` - this will compile `index.ts` into `index.js` which can
|
|
84
|
+
be executed using Node.js. If you run into any errors please open an issue in
|
|
85
|
+
[fastify/help](https://github.com/fastify/help/)
|
|
67
86
|
7. Run `npm run start` to run the Fastify server
|
|
68
87
|
8. You should see `Server listening at http://127.0.0.1:8080` in your console
|
|
69
|
-
9. Try out your server using `curl localhost:8080/ping`, it should return `pong`
|
|
88
|
+
9. Try out your server using `curl localhost:8080/ping`, it should return `pong`
|
|
89
|
+
🏓
|
|
70
90
|
|
|
71
|
-
🎉 You now have a working Typescript Fastify server! This example demonstrates
|
|
91
|
+
🎉 You now have a working Typescript Fastify server! This example demonstrates
|
|
92
|
+
the simplicity of the version 3.x type system. By default, the type system
|
|
93
|
+
assumes you are using an `http` server. The later examples will demonstrate how
|
|
94
|
+
to create more complex servers such as `https` and `http2`, how to specify route
|
|
95
|
+
schemas, and more!
|
|
72
96
|
|
|
73
|
-
> For more examples on initializing Fastify with TypeScript (such as enabling
|
|
97
|
+
> For more examples on initializing Fastify with TypeScript (such as enabling
|
|
98
|
+
> HTTP2) check out the detailed API section [here][Fastify]
|
|
74
99
|
|
|
75
100
|
### Using Generics
|
|
76
101
|
|
|
77
|
-
The type system heavily relies on generic properties to provide the most
|
|
102
|
+
The type system heavily relies on generic properties to provide the most
|
|
103
|
+
accurate development experience. While some may find the overhead a bit
|
|
104
|
+
cumbersome, the tradeoff is worth it! This example will dive into implementing
|
|
105
|
+
generic types for route schemas and the dynamic properties located on the
|
|
106
|
+
route-level `request` object.
|
|
78
107
|
|
|
79
108
|
1. If you did not complete the previous example, follow steps 1-4 to get set up.
|
|
80
109
|
2. Inside `index.ts`, define two interfaces `IQuerystring` and `IHeaders`:
|
|
@@ -88,7 +117,13 @@ The type system heavily relies on generic properties to provide the most accurat
|
|
|
88
117
|
'h-Custom': string;
|
|
89
118
|
}
|
|
90
119
|
```
|
|
91
|
-
3. Using the two interfaces, define a new API route and pass them as generics.
|
|
120
|
+
3. Using the two interfaces, define a new API route and pass them as generics.
|
|
121
|
+
The shorthand route methods (i.e. `.get`) accept a generic object
|
|
122
|
+
`RouteGenericInterface` containing five named properties: `Body`,
|
|
123
|
+
`Querystring`, `Params`, `Headers` and `Reply`. The interfaces `Body`,
|
|
124
|
+
`Querystring`, `Params` and `Headers` will be passed down through the route
|
|
125
|
+
method into the route method handler `request` instance and the `Reply`
|
|
126
|
+
interface to the `reply` instance.
|
|
92
127
|
```typescript
|
|
93
128
|
server.get<{
|
|
94
129
|
Querystring: IQuerystring,
|
|
@@ -108,7 +143,9 @@ The type system heavily relies on generic properties to provide the most accurat
|
|
|
108
143
|
curl localhost:8080/auth?username=admin&password=Password123!
|
|
109
144
|
```
|
|
110
145
|
And it should return back `logged in!`
|
|
111
|
-
6. But wait theres more! The generic interfaces are also available inside route
|
|
146
|
+
6. But wait theres more! The generic interfaces are also available inside route
|
|
147
|
+
level hook methods. Modify the previous route by adding a `preValidation`
|
|
148
|
+
hook:
|
|
112
149
|
```typescript
|
|
113
150
|
server.get<{
|
|
114
151
|
Querystring: IQuerystring,
|
|
@@ -124,25 +161,38 @@ The type system heavily relies on generic properties to provide the most accurat
|
|
|
124
161
|
return `logged in!`
|
|
125
162
|
})
|
|
126
163
|
```
|
|
127
|
-
7. Build and run and query with the `username` query string option set to
|
|
164
|
+
7. Build and run and query with the `username` query string option set to
|
|
165
|
+
anything other than `admin`. The API should now return a HTTP 500 error
|
|
166
|
+
`{"statusCode":500,"error":"Internal Server Error","message":"Must be
|
|
167
|
+
admin"}`
|
|
128
168
|
|
|
129
|
-
🎉 Good work, now you can define interfaces for each route and have strictly
|
|
169
|
+
🎉 Good work, now you can define interfaces for each route and have strictly
|
|
170
|
+
typed request and reply instances. Other parts of the Fastify type system rely
|
|
171
|
+
on generic properties. Make sure to reference the detailed type system
|
|
172
|
+
documentation below to learn more about what is available.
|
|
130
173
|
|
|
131
174
|
### JSON Schema
|
|
132
175
|
|
|
133
|
-
To validate your requests and responses you can use JSON Schema files. If you
|
|
176
|
+
To validate your requests and responses you can use JSON Schema files. If you
|
|
177
|
+
didn't know already, defining schemas for your Fastify routes can increase their
|
|
178
|
+
throughput! Check out the [Validation and
|
|
179
|
+
Serialization](./Validation-and-Serialization.md) documentation for more info.
|
|
134
180
|
|
|
135
|
-
Also it has the advantage to use the defined type within your handlers
|
|
181
|
+
Also it has the advantage to use the defined type within your handlers
|
|
182
|
+
(including pre-validation, etc.).
|
|
136
183
|
|
|
137
184
|
Here are some options how to achieve this.
|
|
138
185
|
|
|
139
186
|
|
|
140
187
|
#### typebox
|
|
141
188
|
|
|
142
|
-
A useful library for building types and a schema at once is
|
|
143
|
-
With typebox you
|
|
189
|
+
A useful library for building types and a schema at once is
|
|
190
|
+
[typebox](https://www.npmjs.com/package/@sinclair/typebox). With typebox you
|
|
191
|
+
define your schema within your code and use them directly as types or schemas as
|
|
192
|
+
you need them.
|
|
144
193
|
|
|
145
|
-
When you want to use it for validation of some payload in a fastify route you
|
|
194
|
+
When you want to use it for validation of some payload in a fastify route you
|
|
195
|
+
can do it as follows:
|
|
146
196
|
|
|
147
197
|
1. Install `typebox` in your project.
|
|
148
198
|
|
|
@@ -150,8 +200,9 @@ When you want to use it for validation of some payload in a fastify route you ca
|
|
|
150
200
|
npm i @sinclair/typebox
|
|
151
201
|
```
|
|
152
202
|
|
|
153
|
-
2. Define the schema you need with `Type` and create the respective type with
|
|
154
|
-
|
|
203
|
+
2. Define the schema you need with `Type` and create the respective type with
|
|
204
|
+
`Static`.
|
|
205
|
+
|
|
155
206
|
```typescript
|
|
156
207
|
import { Static, Type } from '@sinclair/typebox'
|
|
157
208
|
|
|
@@ -177,8 +228,8 @@ When you want to use it for validation of some payload in a fastify route you ca
|
|
|
177
228
|
},
|
|
178
229
|
},
|
|
179
230
|
},
|
|
180
|
-
(
|
|
181
|
-
const { body: user } =
|
|
231
|
+
(request, reply) => {
|
|
232
|
+
const { body: user } = request;
|
|
182
233
|
/* user has type
|
|
183
234
|
* const user: StaticProperties<{
|
|
184
235
|
* name: TString;
|
|
@@ -186,23 +237,29 @@ When you want to use it for validation of some payload in a fastify route you ca
|
|
|
186
237
|
* }>
|
|
187
238
|
*/
|
|
188
239
|
//...
|
|
189
|
-
|
|
240
|
+
reply.status(200).send(user);
|
|
190
241
|
}
|
|
191
242
|
);
|
|
192
243
|
```
|
|
193
244
|
|
|
194
245
|
#### Schemas in JSON Files
|
|
195
246
|
|
|
196
|
-
In the last example we used interfaces to define the types for the request
|
|
247
|
+
In the last example we used interfaces to define the types for the request
|
|
248
|
+
querystring and headers. Many users will already be using JSON Schemas to define
|
|
249
|
+
these properties, and luckily there is a way to transform existing JSON Schemas
|
|
250
|
+
into TypeScript interfaces!
|
|
197
251
|
|
|
198
|
-
1. If you did not complete the 'Getting Started' example, go back and follow
|
|
252
|
+
1. If you did not complete the 'Getting Started' example, go back and follow
|
|
253
|
+
steps 1-4 first.
|
|
199
254
|
2. Install the `json-schema-to-typescript` module:
|
|
200
255
|
|
|
201
256
|
```bash
|
|
202
257
|
npm i -D json-schema-to-typescript
|
|
203
258
|
```
|
|
204
259
|
|
|
205
|
-
3. Create a new folder called `schemas` and add two files `headers.json` and
|
|
260
|
+
3. Create a new folder called `schemas` and add two files `headers.json` and
|
|
261
|
+
`querystring.json`. Copy and paste the following schema definitions into the
|
|
262
|
+
respective files:
|
|
206
263
|
|
|
207
264
|
```json
|
|
208
265
|
{
|
|
@@ -239,8 +296,10 @@ In the last example we used interfaces to define the types for the request query
|
|
|
239
296
|
}
|
|
240
297
|
```
|
|
241
298
|
|
|
242
|
-
`json2ts` is a CLI utility included in `json-schema-to-typescript`. `schemas`
|
|
243
|
-
|
|
299
|
+
`json2ts` is a CLI utility included in `json-schema-to-typescript`. `schemas`
|
|
300
|
+
is the input path, and `types` is the output path.
|
|
301
|
+
5. Run `npm run compile-schemas`. Two new files should have been created in the
|
|
302
|
+
`types` directory.
|
|
244
303
|
6. Update `index.ts` to have the following code:
|
|
245
304
|
|
|
246
305
|
```typescript
|
|
@@ -309,13 +368,17 @@ In the last example we used interfaces to define the types for the request query
|
|
|
309
368
|
console.log(`Server listening at ${address}`)
|
|
310
369
|
})
|
|
311
370
|
```
|
|
312
|
-
Pay special attention to the imports at the top of this file. It might seem
|
|
371
|
+
Pay special attention to the imports at the top of this file. It might seem
|
|
372
|
+
redundant, but you need to import both the schema files and the generated
|
|
373
|
+
interfaces.
|
|
313
374
|
|
|
314
|
-
Great work! Now you can make use of both JSON Schemas and TypeScript
|
|
375
|
+
Great work! Now you can make use of both JSON Schemas and TypeScript
|
|
376
|
+
definitions.
|
|
315
377
|
|
|
316
378
|
#### json-schema-to-ts
|
|
317
379
|
|
|
318
|
-
If you do not want to generate types from your schemas, but want to use them
|
|
380
|
+
If you do not want to generate types from your schemas, but want to use them
|
|
381
|
+
diretly from your code, you can use the package
|
|
319
382
|
[json-schema-to-ts](https://www.npmjs.com/package/json-schema-to-ts).
|
|
320
383
|
|
|
321
384
|
You can install it as dev-dependency.
|
|
@@ -324,7 +387,8 @@ You can install it as dev-dependency.
|
|
|
324
387
|
npm install -D json-schema-to-ts
|
|
325
388
|
```
|
|
326
389
|
|
|
327
|
-
In your code you can define your schema like a normal object. But be aware of
|
|
390
|
+
In your code you can define your schema like a normal object. But be aware of
|
|
391
|
+
making it *const* like explained in the docs of the module.
|
|
328
392
|
|
|
329
393
|
```typescript
|
|
330
394
|
const todo = {
|
|
@@ -338,7 +402,8 @@ const todo = {
|
|
|
338
402
|
} as const;
|
|
339
403
|
```
|
|
340
404
|
|
|
341
|
-
With the provided type `FromSchema` you can build a type from your schema and
|
|
405
|
+
With the provided type `FromSchema` you can build a type from your schema and
|
|
406
|
+
use it in your handler.
|
|
342
407
|
|
|
343
408
|
```typescript
|
|
344
409
|
import { FromSchema } from "json-schema-to-ts";
|
|
@@ -357,7 +422,7 @@ fastify.post<{ Body: FromSchema<typeof todo> }>(
|
|
|
357
422
|
async (request, reply): Promise<void> => {
|
|
358
423
|
|
|
359
424
|
/*
|
|
360
|
-
request.body has type
|
|
425
|
+
request.body has type
|
|
361
426
|
{
|
|
362
427
|
[x: string]: unknown;
|
|
363
428
|
description?: string;
|
|
@@ -368,7 +433,7 @@ fastify.post<{ Body: FromSchema<typeof todo> }>(
|
|
|
368
433
|
|
|
369
434
|
request.body.name // will not throw type error
|
|
370
435
|
request.body.notthere // will throw type error
|
|
371
|
-
|
|
436
|
+
|
|
372
437
|
reply.status(201).send();
|
|
373
438
|
},
|
|
374
439
|
);
|
|
@@ -376,7 +441,13 @@ fastify.post<{ Body: FromSchema<typeof todo> }>(
|
|
|
376
441
|
|
|
377
442
|
### Plugins
|
|
378
443
|
|
|
379
|
-
One of Fastify's most distinguishable features is its extensive plugin
|
|
444
|
+
One of Fastify's most distinguishable features is its extensive plugin
|
|
445
|
+
ecosystem. Plugin types are fully supported, and take advantage of the
|
|
446
|
+
[declaration
|
|
447
|
+
merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html)
|
|
448
|
+
pattern. This example is broken up into three parts: Creating a TypeScript
|
|
449
|
+
Fastify Plugin, Creating Type Definitions for a Fastify Plugin, and Using a
|
|
450
|
+
Fastify Plugin in a TypeScript Project.
|
|
380
451
|
|
|
381
452
|
#### Creating a TypeScript Fastify Plugin
|
|
382
453
|
|
|
@@ -386,7 +457,8 @@ One of Fastify's most distinguishable features is its extensive plugin ecosystem
|
|
|
386
457
|
npm i fastify fastify-plugin
|
|
387
458
|
npm i -D typescript @types/node
|
|
388
459
|
```
|
|
389
|
-
2. Add a `build` script to the `"scripts"` section and `'index.d.ts'` to the
|
|
460
|
+
2. Add a `build` script to the `"scripts"` section and `'index.d.ts'` to the
|
|
461
|
+
`"types"` section of the `package.json` file:
|
|
390
462
|
```json
|
|
391
463
|
{
|
|
392
464
|
"types": "index.d.ts",
|
|
@@ -399,7 +471,8 @@ One of Fastify's most distinguishable features is its extensive plugin ecosystem
|
|
|
399
471
|
```bash
|
|
400
472
|
npx typescript --init
|
|
401
473
|
```
|
|
402
|
-
Once the file is generated, enable the `"declaration"` option in the
|
|
474
|
+
Once the file is generated, enable the `"declaration"` option in the
|
|
475
|
+
`"compilerOptions"` object.
|
|
403
476
|
```json
|
|
404
477
|
{
|
|
405
478
|
"compileOptions": {
|
|
@@ -447,13 +520,20 @@ One of Fastify's most distinguishable features is its extensive plugin ecosystem
|
|
|
447
520
|
// or
|
|
448
521
|
// export default fp(myPluginAsync, '3.x')
|
|
449
522
|
```
|
|
450
|
-
6. Run `npm run build` to compile the plugin code and produce both a JavaScript
|
|
523
|
+
6. Run `npm run build` to compile the plugin code and produce both a JavaScript
|
|
524
|
+
source file and a type definition file.
|
|
451
525
|
7. With the plugin now complete you can [publish to npm] or use it locally.
|
|
452
|
-
> You do not _need_ to publish your plugin to npm to use it. You can include
|
|
526
|
+
> You do not _need_ to publish your plugin to npm to use it. You can include
|
|
527
|
+
> it in a Fastify project and reference it as you would any piece of code! As
|
|
528
|
+
> a TypeScript user, make sure the declaration override exists somewhere that
|
|
529
|
+
> will be included in your project compilation so the TypeScript interpreter
|
|
530
|
+
> can process it.
|
|
453
531
|
|
|
454
532
|
#### Creating Type Definitions for a Fastify Plugin
|
|
455
533
|
|
|
456
|
-
This plugin guide is for Fastify plugins written in JavaScript. The steps
|
|
534
|
+
This plugin guide is for Fastify plugins written in JavaScript. The steps
|
|
535
|
+
outlined in this example are for adding TypeScript support for users consuming
|
|
536
|
+
your plugin.
|
|
457
537
|
|
|
458
538
|
1. Initialize a new npm project and install required dependencies
|
|
459
539
|
```bash
|
|
@@ -461,7 +541,9 @@ This plugin guide is for Fastify plugins written in JavaScript. The steps outlin
|
|
|
461
541
|
npm i fastify-plugin
|
|
462
542
|
```
|
|
463
543
|
2. Create two files `index.js` and `index.d.ts`
|
|
464
|
-
3. Modify the package json to include these files under the `main` and `types`
|
|
544
|
+
3. Modify the package json to include these files under the `main` and `types`
|
|
545
|
+
properties (the name does not have to be `index` explicitly, but it is
|
|
546
|
+
recommended the files have the same name):
|
|
465
547
|
```json
|
|
466
548
|
{
|
|
467
549
|
"main": "index.js",
|
|
@@ -517,25 +599,48 @@ This plugin guide is for Fastify plugins written in JavaScript. The steps outlin
|
|
|
517
599
|
export default myPlugin
|
|
518
600
|
```
|
|
519
601
|
|
|
520
|
-
__Note__: [fastify-plugin](https://github.com/fastify/fastify-plugin) v2.3.0 and
|
|
602
|
+
__Note__: [fastify-plugin](https://github.com/fastify/fastify-plugin) v2.3.0 and
|
|
603
|
+
newer, automatically adds `.default` property and a named export to the exported
|
|
604
|
+
plugin. Be sure to `export default` and `export const myPlugin` in your typings
|
|
605
|
+
to provide the best developer experience. For a complete example you can check
|
|
606
|
+
out
|
|
607
|
+
[fastify-swagger](https://github.com/fastify/fastify-swagger/blob/master/index.d.ts).
|
|
521
608
|
|
|
522
|
-
With those files completed, the plugin is now ready to be consumed by any
|
|
609
|
+
With those files completed, the plugin is now ready to be consumed by any
|
|
610
|
+
TypeScript project!
|
|
523
611
|
|
|
524
|
-
The Fastify plugin system enables developers to decorate the Fastify instance,
|
|
612
|
+
The Fastify plugin system enables developers to decorate the Fastify instance,
|
|
613
|
+
and the request/reply instances. For more information check out this blog post
|
|
614
|
+
on [Declaration Merging and Generic
|
|
615
|
+
Inheritance](https://dev.to/ethanarrowood/is-declaration-merging-and-generic-inheritance-at-the-same-time-impossible-53cp).
|
|
525
616
|
|
|
526
617
|
#### Using a Plugin
|
|
527
618
|
|
|
528
|
-
Using a Fastify plugin in TypeScript is just as easy as using one in JavaScript.
|
|
619
|
+
Using a Fastify plugin in TypeScript is just as easy as using one in JavaScript.
|
|
620
|
+
Import the plugin with `import/from` and you're all set -- except there is one
|
|
621
|
+
exception users should be aware of.
|
|
529
622
|
|
|
530
|
-
Fastify plugins use declaration merging to modify existing Fastify type
|
|
623
|
+
Fastify plugins use declaration merging to modify existing Fastify type
|
|
624
|
+
interfaces (check out the previous two examples for more details). Declaration
|
|
625
|
+
merging is not very _smart_, meaning if the plugin type definition for a plugin
|
|
626
|
+
is within the scope of the TypeScript interpreter, then the plugin types will be
|
|
627
|
+
included **regardless** of if the plugin is being used or not. This is an
|
|
628
|
+
unfortunate limitation of using TypeScript and is unavoidable as of right now.
|
|
531
629
|
|
|
532
630
|
However, there are a couple of suggestions to help improve this experience:
|
|
533
|
-
- Make sure the `no-unused-vars` rule is enabled in
|
|
534
|
-
|
|
631
|
+
- Make sure the `no-unused-vars` rule is enabled in
|
|
632
|
+
[ESLint](https://eslint.org/docs/rules/no-unused-vars) and any imported plugin
|
|
633
|
+
are actually being loaded.
|
|
634
|
+
- Use a module such as [depcheck](https://www.npmjs.com/package/depcheck) or
|
|
635
|
+
[npm-check](https://www.npmjs.com/package/npm-check) to verify plugin
|
|
636
|
+
dependencies are being used somewhere in your project.
|
|
535
637
|
|
|
536
638
|
## Code Completion In Vanilla JavaScript
|
|
537
639
|
|
|
538
|
-
Vanilla JavaScript can use the published types to provide code completion (e.g.
|
|
640
|
+
Vanilla JavaScript can use the published types to provide code completion (e.g.
|
|
641
|
+
[Intellisense](https://code.visualstudio.com/docs/editor/intellisense)) by
|
|
642
|
+
following the [TypeScript JSDoc
|
|
643
|
+
Reference](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html).
|
|
539
644
|
|
|
540
645
|
For example:
|
|
541
646
|
|
|
@@ -548,17 +653,25 @@ module.exports = async function (fastify, { optionA, optionB }) {
|
|
|
548
653
|
|
|
549
654
|
## API Type System Documentation
|
|
550
655
|
|
|
551
|
-
This section is a detailed account of all the types available to you in Fastify
|
|
656
|
+
This section is a detailed account of all the types available to you in Fastify
|
|
657
|
+
version 3.x
|
|
552
658
|
|
|
553
659
|
All `http`, `https`, and `http2` types are inferred from `@types/node`
|
|
554
660
|
|
|
555
|
-
[Generics](#generics) are documented by their default value as well as their
|
|
556
|
-
|
|
557
|
-
|
|
661
|
+
[Generics](#generics) are documented by their default value as well as their
|
|
662
|
+
constraint value(s). Read these articles for more information on TypeScript
|
|
663
|
+
generics.
|
|
664
|
+
- [Generic Parameter
|
|
665
|
+
Default](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-3.html#generic-parameter-defaults)
|
|
666
|
+
- [Generic
|
|
667
|
+
Constraints](https://www.typescriptlang.org/docs/handbook/generics.html#generic-constraints)
|
|
558
668
|
|
|
559
669
|
#### How to import
|
|
560
670
|
|
|
561
|
-
The Fastify API is powered by the `fastify()` method. In JavaScript you would
|
|
671
|
+
The Fastify API is powered by the `fastify()` method. In JavaScript you would
|
|
672
|
+
import it using `const fastify = require('fastify')`. In TypeScript it is
|
|
673
|
+
recommended to use the `import/from` syntax instead so types can be resolved.
|
|
674
|
+
There are a couple supported import methods with the Fastify type system.
|
|
562
675
|
|
|
563
676
|
1. `import fastify from 'fastify'`
|
|
564
677
|
- Types are resolved but not accessible using dot notation
|
|
@@ -585,7 +698,8 @@ The Fastify API is powered by the `fastify()` method. In JavaScript you would im
|
|
|
585
698
|
```
|
|
586
699
|
2. `import * as Fastify from 'fastify'`
|
|
587
700
|
- Types are resolved and accessible using dot notation
|
|
588
|
-
- Calling the main Fastify API method requires a slightly different syntax
|
|
701
|
+
- Calling the main Fastify API method requires a slightly different syntax
|
|
702
|
+
(see example)
|
|
589
703
|
- Example:
|
|
590
704
|
```typescript
|
|
591
705
|
import * as Fastify from 'fastify'
|
|
@@ -594,7 +708,8 @@ The Fastify API is powered by the `fastify()` method. In JavaScript you would im
|
|
|
594
708
|
f.listen(8080, () => { console.log('running') })
|
|
595
709
|
```
|
|
596
710
|
3. `const fastify = require('fastify')`
|
|
597
|
-
- This syntax is valid and will import fastify as expected; however, types
|
|
711
|
+
- This syntax is valid and will import fastify as expected; however, types
|
|
712
|
+
will **not** be resolved
|
|
598
713
|
- Example:
|
|
599
714
|
```typescript
|
|
600
715
|
const fastify = require('fastify')
|
|
@@ -612,7 +727,8 @@ The Fastify API is powered by the `fastify()` method. In JavaScript you would im
|
|
|
612
727
|
|
|
613
728
|
#### Generics
|
|
614
729
|
|
|
615
|
-
Many type definitions share the same generic parameters; they are all
|
|
730
|
+
Many type definitions share the same generic parameters; they are all
|
|
731
|
+
documented, in detail, within this section.
|
|
616
732
|
|
|
617
733
|
Most definitions depend on `@node/types` modules `http`, `https`, and `http2`
|
|
618
734
|
|
|
@@ -621,9 +737,11 @@ Underlying Node.js server type
|
|
|
621
737
|
|
|
622
738
|
Default: `http.Server`
|
|
623
739
|
|
|
624
|
-
Constraints: `http.Server`, `https.Server`, `http2.Http2Server`,
|
|
740
|
+
Constraints: `http.Server`, `https.Server`, `http2.Http2Server`,
|
|
741
|
+
`http2.Http2SecureServer`
|
|
625
742
|
|
|
626
|
-
Enforces generic parameters: [`RawRequest`][RawRequestGeneric],
|
|
743
|
+
Enforces generic parameters: [`RawRequest`][RawRequestGeneric],
|
|
744
|
+
[`RawReply`][RawReplyGeneric]
|
|
627
745
|
|
|
628
746
|
##### RawRequest
|
|
629
747
|
Underlying Node.js request type
|
|
@@ -660,9 +778,16 @@ Constraints: `string | Buffer`
|
|
|
660
778
|
#### Fastify
|
|
661
779
|
|
|
662
780
|
##### fastify<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [Logger][LoggerGeneric]>(opts?: [FastifyServerOptions][FastifyServerOptions]): [FastifyInstance][FastifyInstance]
|
|
663
|
-
[src](
|
|
781
|
+
[src](https://github.com/fastify/fastify/blob/main/fastify.d.ts#L19)
|
|
664
782
|
|
|
665
|
-
The main Fastify API method. By default creates an HTTP server. Utilizing
|
|
783
|
+
The main Fastify API method. By default creates an HTTP server. Utilizing
|
|
784
|
+
discriminant unions and overload methods, the type system will automatically
|
|
785
|
+
infer which type of server (http, https, or http2) is being created purely based
|
|
786
|
+
on the options based to the method (see the examples below for more
|
|
787
|
+
information). It also supports an extensive generic type system to allow the
|
|
788
|
+
user to extend the underlying Node.js Server, Request, and Reply objects.
|
|
789
|
+
Additionally, the `Logger` generic exists for custom log types. See the examples
|
|
790
|
+
and generic breakdown below for more information.
|
|
666
791
|
|
|
667
792
|
###### Example 1: Standard HTTP server
|
|
668
793
|
|
|
@@ -672,7 +797,8 @@ import fastify from 'fastify'
|
|
|
672
797
|
|
|
673
798
|
const server = fastify()
|
|
674
799
|
```
|
|
675
|
-
Check out the Learn By Example - [Getting Started](#getting-started) example for
|
|
800
|
+
Check out the Learn By Example - [Getting Started](#getting-started) example for
|
|
801
|
+
a more detailed http server walkthrough.
|
|
676
802
|
|
|
677
803
|
###### Example 2: HTTPS sever
|
|
678
804
|
|
|
@@ -682,7 +808,9 @@ Check out the Learn By Example - [Getting Started](#getting-started) example for
|
|
|
682
808
|
import path from 'path'
|
|
683
809
|
import fastify from 'fastify'
|
|
684
810
|
```
|
|
685
|
-
2. Follow the steps in this official [Node.js https server
|
|
811
|
+
2. Follow the steps in this official [Node.js https server
|
|
812
|
+
guide](https://nodejs.org/en/knowledge/HTTP/servers/how-to-create-a-HTTPS-server/)
|
|
813
|
+
to create the `key.pem` and `cert.pem` files
|
|
686
814
|
3. Instantiate a Fastify https server and add a route:
|
|
687
815
|
```typescript
|
|
688
816
|
const server = fastify({
|
|
@@ -704,11 +832,15 @@ Check out the Learn By Example - [Getting Started](#getting-started) example for
|
|
|
704
832
|
console.log(`Server listening at ${address}`)
|
|
705
833
|
})
|
|
706
834
|
```
|
|
707
|
-
4. Build and run! Test your server out by querying with: `curl -k
|
|
835
|
+
4. Build and run! Test your server out by querying with: `curl -k
|
|
836
|
+
https://localhost:8080`
|
|
708
837
|
|
|
709
838
|
###### Example 3: HTTP2 server
|
|
710
839
|
|
|
711
|
-
There are two types of HTTP2 server types, insecure and secure. Both require
|
|
840
|
+
There are two types of HTTP2 server types, insecure and secure. Both require
|
|
841
|
+
specifying the `http2` property as `true` in the `options` object. The `https`
|
|
842
|
+
property is used for creating a secure http2 server; omitting the `https`
|
|
843
|
+
property will create an insecure http2 server.
|
|
712
844
|
|
|
713
845
|
```typescript
|
|
714
846
|
const insecureServer = fastify({ http2: true })
|
|
@@ -718,11 +850,15 @@ const secureServer = fastify({
|
|
|
718
850
|
})
|
|
719
851
|
```
|
|
720
852
|
|
|
721
|
-
For more details on using HTTP2 check out the Fastify [HTTP2](HTTP2.md)
|
|
853
|
+
For more details on using HTTP2 check out the Fastify [HTTP2](./HTTP2.md)
|
|
854
|
+
documentation page.
|
|
722
855
|
|
|
723
856
|
###### Example 4: Extended HTTP server
|
|
724
857
|
|
|
725
|
-
Not only can you specify the server type, but also the request and reply types.
|
|
858
|
+
Not only can you specify the server type, but also the request and reply types.
|
|
859
|
+
Thus, allowing you to specify special properties, methods, and more! When
|
|
860
|
+
specified at server instantiation, the custom type becomes available on all
|
|
861
|
+
further instances of the custom type.
|
|
726
862
|
```typescript
|
|
727
863
|
import fastify from 'fastify'
|
|
728
864
|
import http from 'http'
|
|
@@ -741,9 +877,15 @@ server.get('/', async (request, reply) => {
|
|
|
741
877
|
|
|
742
878
|
###### Example 5: Specifying logger types
|
|
743
879
|
|
|
744
|
-
Fastify uses [Pino](https://getpino.io/#/) logging library under the hood. Some
|
|
880
|
+
Fastify uses [Pino](https://getpino.io/#/) logging library under the hood. Some
|
|
881
|
+
of it's properties can be configured via `logger` field when constructing
|
|
882
|
+
Fastify's instance. If properties you need aren't exposed, it's also possible to
|
|
883
|
+
pass a preconfigured external instance of Pino (or any other compatible logger)
|
|
884
|
+
to Fastify via the same field. This allows creating custom serializers as well,
|
|
885
|
+
see the [Logging](./Logging.md) documentation for more info.
|
|
745
886
|
|
|
746
|
-
To use an external instance of Pino, add `@types/pino` to devDependencies and
|
|
887
|
+
To use an external instance of Pino, add `@types/pino` to devDependencies and
|
|
888
|
+
pass the instance to `logger` field:
|
|
747
889
|
|
|
748
890
|
```typescript
|
|
749
891
|
import fastify from 'fastify'
|
|
@@ -766,19 +908,21 @@ server.get('/', async (request, reply) => {
|
|
|
766
908
|
---
|
|
767
909
|
|
|
768
910
|
##### fastify.HTTPMethods
|
|
769
|
-
[src](
|
|
911
|
+
[src](https://github.com/fastify/fastify/blob/main/types/utils.d.ts#L8)
|
|
770
912
|
|
|
771
|
-
Union type of: `'DELETE' | 'GET' | 'HEAD' | 'PATCH' | 'POST' | 'PUT' |
|
|
913
|
+
Union type of: `'DELETE' | 'GET' | 'HEAD' | 'PATCH' | 'POST' | 'PUT' |
|
|
914
|
+
'OPTIONS'`
|
|
772
915
|
|
|
773
916
|
##### fastify.RawServerBase
|
|
774
|
-
[src](
|
|
917
|
+
[src](https://github.com/fastify/fastify/blob/main/types/utils.d.ts#L13)
|
|
775
918
|
|
|
776
919
|
Dependant on `@types/node` modules `http`, `https`, `http2`
|
|
777
920
|
|
|
778
|
-
Union type of: `http.Server | https.Server | http2.Http2Server |
|
|
921
|
+
Union type of: `http.Server | https.Server | http2.Http2Server |
|
|
922
|
+
http2.Http2SecureServer`
|
|
779
923
|
|
|
780
924
|
##### fastify.RawServerDefault
|
|
781
|
-
[src](
|
|
925
|
+
[src](https://github.com/fastify/fastify/blob/main/types/utils.d.ts#L18)
|
|
782
926
|
|
|
783
927
|
Dependant on `@types/node` modules `http`
|
|
784
928
|
|
|
@@ -788,34 +932,53 @@ Type alias for `http.Server`
|
|
|
788
932
|
|
|
789
933
|
##### fastify.FastifyServerOptions<[RawServer][RawServerGeneric], [Logger][LoggerGeneric]>
|
|
790
934
|
|
|
791
|
-
[src](
|
|
935
|
+
[src](https://github.com/fastify/fastify/blob/main/fastify.d.ts#L29)
|
|
792
936
|
|
|
793
|
-
An interface of properties used in the instantiation of the Fastify server. Is
|
|
937
|
+
An interface of properties used in the instantiation of the Fastify server. Is
|
|
938
|
+
used in the main [`fastify()`][Fastify] method. The `RawServer` and `Logger`
|
|
939
|
+
generic parameters are passed down through that method.
|
|
794
940
|
|
|
795
|
-
See the main [fastify][Fastify] method type definition section for examples on
|
|
941
|
+
See the main [fastify][Fastify] method type definition section for examples on
|
|
942
|
+
instantiating a Fastify server with TypeScript.
|
|
796
943
|
|
|
797
944
|
##### fastify.FastifyInstance<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RequestGeneric][FastifyRequestGenericInterface], [Logger][LoggerGeneric]>
|
|
798
945
|
|
|
799
|
-
[src](
|
|
946
|
+
[src](https://github.com/fastify/fastify/blob/main/types/instance.d.ts#L16)
|
|
800
947
|
|
|
801
|
-
Interface that represents the Fastify server object. This is the returned server
|
|
948
|
+
Interface that represents the Fastify server object. This is the returned server
|
|
949
|
+
instance from the [`fastify()`][Fastify] method. This type is an interface so it
|
|
950
|
+
can be extended via [declaration
|
|
951
|
+
merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html)
|
|
952
|
+
if your code makes use of the `decorate` method.
|
|
802
953
|
|
|
803
|
-
Through the use of generic cascading, all methods attached to the instance
|
|
954
|
+
Through the use of generic cascading, all methods attached to the instance
|
|
955
|
+
inherit the generic properties from instantiation. This means that by specifying
|
|
956
|
+
the server, request, or reply types, all methods will know how to type those
|
|
957
|
+
objects.
|
|
804
958
|
|
|
805
|
-
Check out the main [Learn by Example](#learn-by-example) section for detailed
|
|
959
|
+
Check out the main [Learn by Example](#learn-by-example) section for detailed
|
|
960
|
+
guides, or the more simplified [fastify][Fastify] method examples for additional
|
|
961
|
+
details on this interface.
|
|
806
962
|
|
|
807
963
|
---
|
|
808
964
|
|
|
809
965
|
#### Request
|
|
810
966
|
|
|
811
967
|
##### fastify.FastifyRequest<[RequestGeneric][FastifyRequestGenericInterface], [RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric]>
|
|
812
|
-
[src](
|
|
968
|
+
[src](https://github.com/fastify/fastify/blob/main/types/request.d.ts#L15)
|
|
813
969
|
|
|
814
|
-
This interface contains properties of Fastify request object. The properties
|
|
970
|
+
This interface contains properties of Fastify request object. The properties
|
|
971
|
+
added here disregard what kind of request object (http vs http2) and disregard
|
|
972
|
+
what route level it is serving; thus calling `request.body` inside a GET request
|
|
973
|
+
will not throw an error (but good luck sending a GET request with a body 😉).
|
|
815
974
|
|
|
816
|
-
If you need to add custom properties to the `FastifyRequest` object (such as
|
|
975
|
+
If you need to add custom properties to the `FastifyRequest` object (such as
|
|
976
|
+
when using the [`decorateRequest`][DecorateRequest] method) you need to use
|
|
977
|
+
declaration merging on this interface.
|
|
817
978
|
|
|
818
|
-
A basic example is provided in the [`FastifyRequest`][FastifyRequest] section.
|
|
979
|
+
A basic example is provided in the [`FastifyRequest`][FastifyRequest] section.
|
|
980
|
+
For a more detailed example check out the Learn By Example section:
|
|
981
|
+
[Plugins](#plugins)
|
|
819
982
|
|
|
820
983
|
###### Example
|
|
821
984
|
```typescript
|
|
@@ -848,9 +1011,14 @@ server.get('/typedRequest', async (request: CustomRequest, reply: FastifyReply)
|
|
|
848
1011
|
```
|
|
849
1012
|
|
|
850
1013
|
##### fastify.RequestGenericInterface
|
|
851
|
-
[src](
|
|
1014
|
+
[src](https://github.com/fastify/fastify/blob/main/types/request.d.ts#L4)
|
|
852
1015
|
|
|
853
|
-
Fastify request objects have four dynamic properties: `body`, `params`, `query`,
|
|
1016
|
+
Fastify request objects have four dynamic properties: `body`, `params`, `query`,
|
|
1017
|
+
and `headers`. Their respective types are assignable through this interface. It
|
|
1018
|
+
is a named property interface enabling the developer to ignore the properties
|
|
1019
|
+
they do not want to specify. All omitted properties are defaulted to `unknown`.
|
|
1020
|
+
The corresponding property names are: `Body`, `Querystring`, `Params`,
|
|
1021
|
+
`Headers`.
|
|
854
1022
|
|
|
855
1023
|
```typescript
|
|
856
1024
|
import fastify, { RequestGenericInterface } from 'fastify'
|
|
@@ -869,16 +1037,19 @@ server.get<requestGeneric>('/', async (request, reply) => {
|
|
|
869
1037
|
})
|
|
870
1038
|
```
|
|
871
1039
|
|
|
872
|
-
If you want to see a detailed example of using this interface check out the
|
|
1040
|
+
If you want to see a detailed example of using this interface check out the
|
|
1041
|
+
Learn by Example section: [JSON Schema](#jsonschema).
|
|
873
1042
|
|
|
874
1043
|
##### fastify.RawRequestDefaultExpression\<[RawServer][RawServerGeneric]\>
|
|
875
|
-
[src](
|
|
1044
|
+
[src](https://github.com/fastify/fastify/blob/main/types/utils.d.ts#L23)
|
|
876
1045
|
|
|
877
1046
|
Dependant on `@types/node` modules `http`, `https`, `http2`
|
|
878
1047
|
|
|
879
1048
|
Generic parameter `RawServer` defaults to [`RawServerDefault`][RawServerDefault]
|
|
880
1049
|
|
|
881
|
-
If `RawServer` is of type `http.Server` or `https.Server`, then this expression
|
|
1050
|
+
If `RawServer` is of type `http.Server` or `https.Server`, then this expression
|
|
1051
|
+
returns `http.IncomingMessage`, otherwise, it returns
|
|
1052
|
+
`http2.Http2ServerRequest`.
|
|
882
1053
|
|
|
883
1054
|
```typescript
|
|
884
1055
|
import http from 'http'
|
|
@@ -894,13 +1065,19 @@ RawRequestDefaultExpression<http2.Http2Server> // -> http2.Http2ServerRequest
|
|
|
894
1065
|
#### Reply
|
|
895
1066
|
|
|
896
1067
|
##### fastify.FastifyReply<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>
|
|
897
|
-
[src](
|
|
1068
|
+
[src](https://github.com/fastify/fastify/blob/main/types/reply.d.ts#L32)
|
|
898
1069
|
|
|
899
|
-
This interface contains the custom properties that Fastify adds to the standard
|
|
1070
|
+
This interface contains the custom properties that Fastify adds to the standard
|
|
1071
|
+
Node.js reply object. The properties added here disregard what kind of reply
|
|
1072
|
+
object (http vs http2).
|
|
900
1073
|
|
|
901
|
-
If you need to add custom properties to the FastifyReply object (such as when
|
|
1074
|
+
If you need to add custom properties to the FastifyReply object (such as when
|
|
1075
|
+
using the `decorateReply` method) you need to use declaration merging on this
|
|
1076
|
+
interface.
|
|
902
1077
|
|
|
903
|
-
A basic example is provided in the [`FastifyReply`][FastifyReply] section. For a
|
|
1078
|
+
A basic example is provided in the [`FastifyReply`][FastifyReply] section. For a
|
|
1079
|
+
more detailed example check out the Learn By Example section:
|
|
1080
|
+
[Plugins](#plugins)
|
|
904
1081
|
|
|
905
1082
|
###### Example
|
|
906
1083
|
```typescript
|
|
@@ -924,13 +1101,15 @@ declare module 'fastify' {
|
|
|
924
1101
|
```
|
|
925
1102
|
|
|
926
1103
|
##### fastify.RawReplyDefaultExpression<[RawServer][RawServerGeneric]>
|
|
927
|
-
[src](
|
|
1104
|
+
[src](https://github.com/fastify/fastify/blob/main/types/utils.d.ts#L27)
|
|
928
1105
|
|
|
929
1106
|
Dependant on `@types/node` modules `http`, `https`, `http2`
|
|
930
1107
|
|
|
931
1108
|
Generic parameter `RawServer` defaults to [`RawServerDefault`][RawServerDefault]
|
|
932
1109
|
|
|
933
|
-
If `RawServer` is of type `http.Server` or `https.Server`, then this expression
|
|
1110
|
+
If `RawServer` is of type `http.Server` or `https.Server`, then this expression
|
|
1111
|
+
returns `http.ServerResponse`, otherwise, it returns
|
|
1112
|
+
`http2.Http2ServerResponse`.
|
|
934
1113
|
|
|
935
1114
|
```typescript
|
|
936
1115
|
import http from 'http'
|
|
@@ -945,44 +1124,61 @@ RawReplyDefaultExpression<http2.Http2Server> // -> http2.Http2ServerResponse
|
|
|
945
1124
|
|
|
946
1125
|
#### Plugin
|
|
947
1126
|
|
|
948
|
-
Fastify allows the user to extend its functionalities with plugins. A plugin can
|
|
1127
|
+
Fastify allows the user to extend its functionalities with plugins. A plugin can
|
|
1128
|
+
be a set of routes, a server decorator or whatever. To activate plugins, use the
|
|
1129
|
+
[`fastify.register()`][FastifyRegister] method.
|
|
949
1130
|
|
|
950
|
-
When creating plugins for Fastify, it is recommended to use the `fastify-plugin`
|
|
1131
|
+
When creating plugins for Fastify, it is recommended to use the `fastify-plugin`
|
|
1132
|
+
module. Additionally, there is a guide to creating plugins with TypeScript and
|
|
1133
|
+
Fastify available in the Learn by Example, [Plugins](#plugins) section.
|
|
951
1134
|
|
|
952
1135
|
##### fastify.FastifyPluginCallback<[Options][FastifyPluginOptions]>
|
|
953
|
-
[src](
|
|
1136
|
+
[src](https://github.com/fastify/fastify/blob/main/types/plugin.d.ts#L9)
|
|
954
1137
|
|
|
955
|
-
Interface method definition used within the
|
|
1138
|
+
Interface method definition used within the
|
|
1139
|
+
[`fastify.register()`][FastifyRegister] method.
|
|
956
1140
|
|
|
957
1141
|
##### fastify.FastifyPluginAsync<[Options][FastifyPluginOptions]>
|
|
958
|
-
[src](
|
|
1142
|
+
[src](https://github.com/fastify/fastify/blob/main/types/plugin.d.ts#L20)
|
|
959
1143
|
|
|
960
|
-
Interface method definition used within the
|
|
1144
|
+
Interface method definition used within the
|
|
1145
|
+
[`fastify.register()`][FastifyRegister] method.
|
|
961
1146
|
|
|
962
1147
|
##### fastify.FastifyPlugin<[Options][FastifyPluginOptions]>
|
|
963
|
-
[src](
|
|
1148
|
+
[src](https://github.com/fastify/fastify/blob/main/types/plugin.d.ts#L29)
|
|
964
1149
|
|
|
965
|
-
Interface method definition used within the
|
|
966
|
-
Document deprecated in favor of
|
|
967
|
-
`
|
|
1150
|
+
Interface method definition used within the
|
|
1151
|
+
[`fastify.register()`][FastifyRegister] method. Document deprecated in favor of
|
|
1152
|
+
`FastifyPluginCallback` and `FastifyPluginAsync` since general `FastifyPlugin`
|
|
1153
|
+
doesn't properly infer types for async functions.
|
|
968
1154
|
|
|
969
1155
|
##### fastify.FastifyPluginOptions
|
|
970
|
-
[src](
|
|
1156
|
+
[src](https://github.com/fastify/fastify/blob/main/types/plugin.d.ts#L31)
|
|
971
1157
|
|
|
972
|
-
A loosely typed object used to constrain the `options` parameter of
|
|
1158
|
+
A loosely typed object used to constrain the `options` parameter of
|
|
1159
|
+
[`fastify.register()`][FastifyRegister] to an object. When creating a plugin,
|
|
1160
|
+
define its options as an extension of this interface (`interface MyPluginOptions
|
|
1161
|
+
extends FastifyPluginOptions`) so they can be passed to the register method.
|
|
973
1162
|
|
|
974
1163
|
---
|
|
975
1164
|
|
|
976
1165
|
#### Register
|
|
977
1166
|
|
|
978
1167
|
##### fastify.FastifyRegister(plugin: [FastifyPluginCallback][FastifyPluginCallback], opts: [FastifyRegisterOptions][FastifyRegisterOptions])
|
|
979
|
-
[src](
|
|
1168
|
+
[src](https://github.com/fastify/fastify/blob/main/types/register.d.ts#L9)
|
|
980
1169
|
##### fastify.FastifyRegister(plugin: [FastifyPluginAsync][FastifyPluginAsync], opts: [FastifyRegisterOptions][FastifyRegisterOptions])
|
|
981
|
-
[src](
|
|
1170
|
+
[src](https://github.com/fastify/fastify/blob/main/types/register.d.ts#L9)
|
|
982
1171
|
##### fastify.FastifyRegister(plugin: [FastifyPlugin][FastifyPlugin], opts: [FastifyRegisterOptions][FastifyRegisterOptions])
|
|
983
|
-
[src](
|
|
1172
|
+
[src](https://github.com/fastify/fastify/blob/main/types/register.d.ts#L9)
|
|
984
1173
|
|
|
985
|
-
This type interface specifies the type for the
|
|
1174
|
+
This type interface specifies the type for the
|
|
1175
|
+
[`fastify.register()`](./Server.md#register) method. The type interface returns
|
|
1176
|
+
a function signature with an underlying generic `Options` which is defaulted to
|
|
1177
|
+
[FastifyPluginOptions][FastifyPluginOptions]. It infers this generic from the
|
|
1178
|
+
FastifyPlugin parameter when calling this function so there is no need to
|
|
1179
|
+
specify the underlying generic. The options parameter is the intersection of the
|
|
1180
|
+
plugin's options and two additional optional properties: `prefix: string` and
|
|
1181
|
+
`logLevel`: [LogLevel][LogLevel].
|
|
986
1182
|
|
|
987
1183
|
Below is an example of the options inference in action:
|
|
988
1184
|
|
|
@@ -998,34 +1194,43 @@ fastify().register(plugin, {}) // Error - options object is missing required pro
|
|
|
998
1194
|
fastify().register(plugin, { option1: '', option2: true }) // OK - options object contains required properties
|
|
999
1195
|
```
|
|
1000
1196
|
|
|
1001
|
-
See the Learn By Example, [Plugins](#plugins) section for more detailed examples
|
|
1197
|
+
See the Learn By Example, [Plugins](#plugins) section for more detailed examples
|
|
1198
|
+
of creating TypeScript plugins in Fastify.
|
|
1002
1199
|
|
|
1003
|
-
##### fastify.FastifyRegisterOptions
|
|
1004
|
-
[src](
|
|
1200
|
+
##### fastify.FastifyRegisterOptions
|
|
1201
|
+
[src](https://github.com/fastify/fastify/blob/main/types/register.d.ts#L16)
|
|
1005
1202
|
|
|
1006
|
-
This type is the intersection of the `Options` generic and a non-exported
|
|
1203
|
+
This type is the intersection of the `Options` generic and a non-exported
|
|
1204
|
+
interface `RegisterOptions` that specifies two optional properties: `prefix:
|
|
1205
|
+
string` and `logLevel`: [LogLevel][LogLevel]. This type can also be specified as
|
|
1206
|
+
a function that returns the previously described intersection.
|
|
1007
1207
|
|
|
1008
1208
|
---
|
|
1009
1209
|
|
|
1010
1210
|
#### Logger
|
|
1011
1211
|
|
|
1012
|
-
Check out the [Specifying Logger Types](#example-5-specifying-logger-types)
|
|
1212
|
+
Check out the [Specifying Logger Types](#example-5-specifying-logger-types)
|
|
1213
|
+
example for more details on specifying a custom logger.
|
|
1013
1214
|
|
|
1014
1215
|
##### fastify.FastifyLoggerOptions<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric]>
|
|
1015
1216
|
|
|
1016
|
-
[src](
|
|
1217
|
+
[src](https://github.com/fastify/fastify/blob/main/types/logger.d.ts#L17)
|
|
1017
1218
|
|
|
1018
|
-
An interface definition for the internal Fastify logger. It is emulative of the
|
|
1219
|
+
An interface definition for the internal Fastify logger. It is emulative of the
|
|
1220
|
+
[Pino.js](https://getpino.io/#/) logger. When enabled through server options,
|
|
1221
|
+
use it following the general [logger](./Logging.md) documentation.
|
|
1019
1222
|
|
|
1020
1223
|
##### fastify.FastifyLogFn
|
|
1021
1224
|
|
|
1022
|
-
[src](
|
|
1225
|
+
[src](https://github.com/fastify/fastify/blob/main/types/logger.d.ts#L7)
|
|
1023
1226
|
|
|
1024
|
-
An overload function interface that implements the two ways Fastify calls log
|
|
1227
|
+
An overload function interface that implements the two ways Fastify calls log
|
|
1228
|
+
methods. This interface is passed to all associated log level properties on the
|
|
1229
|
+
FastifyLoggerOptions object.
|
|
1025
1230
|
|
|
1026
1231
|
##### fastify.LogLevel
|
|
1027
1232
|
|
|
1028
|
-
[src](
|
|
1233
|
+
[src](https://github.com/fastify/fastify/blob/main/types/logger.d.ts#L12)
|
|
1029
1234
|
|
|
1030
1235
|
Union type of: `'info' | 'error' | 'debug' | 'fatal' | 'warn' | 'trace'`
|
|
1031
1236
|
|
|
@@ -1033,54 +1238,73 @@ Union type of: `'info' | 'error' | 'debug' | 'fatal' | 'warn' | 'trace'`
|
|
|
1033
1238
|
|
|
1034
1239
|
#### Context
|
|
1035
1240
|
|
|
1036
|
-
The context type definition is similar to the other highly dynamic pieces of the
|
|
1241
|
+
The context type definition is similar to the other highly dynamic pieces of the
|
|
1242
|
+
type system. Route context is available in the route handler method.
|
|
1037
1243
|
|
|
1038
1244
|
##### fastify.FastifyContext
|
|
1039
1245
|
|
|
1040
|
-
[src](
|
|
1246
|
+
[src](https://github.com/fastify/fastify/blob/main/types/context.d.ts#L6)
|
|
1041
1247
|
|
|
1042
|
-
An interface with a single required property `config` that is set by default to
|
|
1248
|
+
An interface with a single required property `config` that is set by default to
|
|
1249
|
+
`unknown`. Can be specified either using a generic or an overload.
|
|
1043
1250
|
|
|
1044
|
-
This type definition is potentially incomplete. If you are using it and can
|
|
1251
|
+
This type definition is potentially incomplete. If you are using it and can
|
|
1252
|
+
provide more details on how to improve the definition, we strongly encourage you
|
|
1253
|
+
to open an issue in the main
|
|
1254
|
+
[fastify/fastify](https://github.com/fastify/fastify) repository. Thank you in
|
|
1255
|
+
advanced!
|
|
1045
1256
|
|
|
1046
1257
|
---
|
|
1047
1258
|
|
|
1048
1259
|
#### Routing
|
|
1049
1260
|
|
|
1050
|
-
One of the core principles in Fastify is its routing capabilities. Most of the
|
|
1261
|
+
One of the core principles in Fastify is its routing capabilities. Most of the
|
|
1262
|
+
types defined in this section are used under-the-hood by the Fastify instance
|
|
1263
|
+
`.route` and `.get/.post/.etc` methods.
|
|
1051
1264
|
|
|
1052
1265
|
##### fastify.RouteHandlerMethod<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>
|
|
1053
1266
|
|
|
1054
|
-
[src](
|
|
1267
|
+
[src](https://github.com/fastify/fastify/blob/main/types/route.d.ts#L105)
|
|
1055
1268
|
|
|
1056
|
-
A type declaration for the route handler methods. Has two arguments, `request`
|
|
1269
|
+
A type declaration for the route handler methods. Has two arguments, `request`
|
|
1270
|
+
and `reply` which are typed by `FastifyRequest` and `FastifyReply` respectfully.
|
|
1271
|
+
The generics parameters are passed through to these arguments. The method
|
|
1272
|
+
returns either `void` or `Promise<any>` for synchronous and asynchronous
|
|
1273
|
+
handlers respectfully.
|
|
1057
1274
|
|
|
1058
1275
|
##### fastify.RouteOptions<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>
|
|
1059
1276
|
|
|
1060
|
-
[src](
|
|
1277
|
+
[src](https://github.com/fastify/fastify/blob/main/types/route.d.ts#L78)
|
|
1061
1278
|
|
|
1062
|
-
An interface than extends RouteShorthandOptions and adds the follow three
|
|
1063
|
-
|
|
1279
|
+
An interface than extends RouteShorthandOptions and adds the follow three
|
|
1280
|
+
required properties:
|
|
1281
|
+
1. `method` which corresponds to a singular [HTTPMethod][HTTPMethods] or a list
|
|
1282
|
+
of [HTTPMethods][HTTPMethods]
|
|
1064
1283
|
2. `url` a string for the route
|
|
1065
|
-
3. `handler` the route handler method, see [RouteHandlerMethod][] for more
|
|
1284
|
+
3. `handler` the route handler method, see [RouteHandlerMethod][] for more
|
|
1285
|
+
details
|
|
1066
1286
|
|
|
1067
1287
|
##### fastify.RouteShorthandMethod<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric]>
|
|
1068
1288
|
|
|
1069
|
-
[src](
|
|
1289
|
+
[src](https://github.com/fastify/fastify/blob/main/types/route.d.ts#12)
|
|
1070
1290
|
|
|
1071
|
-
An overloaded function interface for three kinds of shorthand route methods to
|
|
1291
|
+
An overloaded function interface for three kinds of shorthand route methods to
|
|
1292
|
+
be used in conjunction with the `.get/.post/.etc` methods.
|
|
1072
1293
|
|
|
1073
1294
|
##### fastify.RouteShorthandOptions<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>
|
|
1074
1295
|
|
|
1075
|
-
[src](
|
|
1296
|
+
[src](https://github.com/fastify/fastify/blob/main/types/route.d.ts#55)
|
|
1076
1297
|
|
|
1077
|
-
An interface that covers all of the base options for a route. Each property on
|
|
1298
|
+
An interface that covers all of the base options for a route. Each property on
|
|
1299
|
+
this interface is optional, and it serves as the base for the RouteOptions and
|
|
1300
|
+
RouteShorthandOptionsWithHandler interfaces.
|
|
1078
1301
|
|
|
1079
1302
|
##### fastify.RouteShorthandOptionsWithHandler<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>
|
|
1080
1303
|
|
|
1081
|
-
[src](
|
|
1304
|
+
[src](https://github.com/fastify/fastify/blob/main/types/route.d.ts#93)
|
|
1082
1305
|
|
|
1083
|
-
This interface adds a single, required property to the RouteShorthandOptions
|
|
1306
|
+
This interface adds a single, required property to the RouteShorthandOptions
|
|
1307
|
+
interface `handler` which is of type RouteHandlerMethod
|
|
1084
1308
|
|
|
1085
1309
|
---
|
|
1086
1310
|
|
|
@@ -1092,25 +1316,30 @@ A generic type that is either a `string` or `Buffer`
|
|
|
1092
1316
|
|
|
1093
1317
|
##### fastify.FastifyBodyParser<[RawBody][RawBodyGeneric], [RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric]>
|
|
1094
1318
|
|
|
1095
|
-
[src](
|
|
1319
|
+
[src](https://github.com/fastify/fastify/blob/main/types/content-type-parser.d.ts#L7)
|
|
1096
1320
|
|
|
1097
|
-
A function type definition for specifying a body parser method. Use the
|
|
1321
|
+
A function type definition for specifying a body parser method. Use the
|
|
1322
|
+
`RawBody` generic to specify the type of the body being parsed.
|
|
1098
1323
|
|
|
1099
1324
|
##### fastify.FastifyContentTypeParser<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric]>
|
|
1100
1325
|
|
|
1101
|
-
[src](
|
|
1326
|
+
[src](https://github.com/fastify/fastify/blob/main/types/content-type-parser.d.ts#L17)
|
|
1102
1327
|
|
|
1103
|
-
A function type definition for specifying a body parser method. Content is typed
|
|
1328
|
+
A function type definition for specifying a body parser method. Content is typed
|
|
1329
|
+
via the `RawRequest` generic.
|
|
1104
1330
|
|
|
1105
1331
|
##### fastify.AddContentTypeParser<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric]>
|
|
1106
1332
|
|
|
1107
|
-
[src](
|
|
1333
|
+
[src](https://github.com/fastify/fastify/blob/main/types/content-type-parser.d.ts#L46)
|
|
1108
1334
|
|
|
1109
|
-
An overloaded interface function definition for the `addContentTypeParser`
|
|
1335
|
+
An overloaded interface function definition for the `addContentTypeParser`
|
|
1336
|
+
method. If `parseAs` is passed to the `opts` parameter, the definition uses
|
|
1337
|
+
[FastifyBodyParser][] for the `parser` parameter; otherwise, it uses
|
|
1338
|
+
[FastifyContentTypeParser][].
|
|
1110
1339
|
|
|
1111
1340
|
##### fastify.hasContentTypeParser
|
|
1112
1341
|
|
|
1113
|
-
[src](
|
|
1342
|
+
[src](https://github.com/fastify/fastify/blob/main/types/content-type-parser.d.ts#L63)
|
|
1114
1343
|
|
|
1115
1344
|
A method for checking the existence of a type parser of a certain content type
|
|
1116
1345
|
|
|
@@ -1120,17 +1349,20 @@ A method for checking the existence of a type parser of a certain content type
|
|
|
1120
1349
|
|
|
1121
1350
|
##### fastify.FastifyError
|
|
1122
1351
|
|
|
1123
|
-
[src](
|
|
1352
|
+
[src](https://github.com/fastify/fastify/blob/main/types/error.d.ts#L17)
|
|
1124
1353
|
|
|
1125
|
-
FastifyError is a custom error object that includes status code and validation
|
|
1354
|
+
FastifyError is a custom error object that includes status code and validation
|
|
1355
|
+
results.
|
|
1126
1356
|
|
|
1127
|
-
It extends the Node.js `Error` type, and adds two additional, optional
|
|
1357
|
+
It extends the Node.js `Error` type, and adds two additional, optional
|
|
1358
|
+
properties: `statusCode: number` and `validation: ValiationResult[]`.
|
|
1128
1359
|
|
|
1129
1360
|
##### fastify.ValidationResult
|
|
1130
1361
|
|
|
1131
|
-
[src](
|
|
1362
|
+
[src](https://github.com/fastify/fastify/blob/main/types/error.d.ts#L4)
|
|
1132
1363
|
|
|
1133
|
-
The route validation internally relies upon Ajv, which is a high-performance
|
|
1364
|
+
The route validation internally relies upon Ajv, which is a high-performance
|
|
1365
|
+
JSON schema validator.
|
|
1134
1366
|
|
|
1135
1367
|
This interface is passed to instance of FastifyError.
|
|
1136
1368
|
|
|
@@ -1140,91 +1372,119 @@ This interface is passed to instance of FastifyError.
|
|
|
1140
1372
|
|
|
1141
1373
|
##### fastify.onRequestHookHandler<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>(request: [FastifyRequest][FastifyRequest], reply: [FastifyReply][FastifyReply], done: (err?: [FastifyError][FastifyError]) => void): Promise\<unknown\> | void
|
|
1142
1374
|
|
|
1143
|
-
[src](
|
|
1375
|
+
[src](https://github.com/fastify/fastify/blob/main/types/hooks.d.ts#L17)
|
|
1144
1376
|
|
|
1145
|
-
`onRequest` is the first hook to be executed in the request lifecycle. There was
|
|
1377
|
+
`onRequest` is the first hook to be executed in the request lifecycle. There was
|
|
1378
|
+
no previous hook, the next hook will be `preParsing`.
|
|
1146
1379
|
|
|
1147
|
-
Notice: in the `onRequest` hook, request.body will always be null, because the
|
|
1380
|
+
Notice: in the `onRequest` hook, request.body will always be null, because the
|
|
1381
|
+
body parsing happens before the `preHandler` hook.
|
|
1148
1382
|
|
|
1149
1383
|
##### fastify.preParsingHookHandler<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>(request: [FastifyRequest][FastifyRequest], reply: [FastifyReply][FastifyReply], done: (err?: [FastifyError][FastifyError]) => void): Promise\<unknown\> | void
|
|
1150
1384
|
|
|
1151
|
-
[src](
|
|
1385
|
+
[src](https://github.com/fastify/fastify/blob/main/types/hooks.d.ts#L35)
|
|
1152
1386
|
|
|
1153
|
-
preParsing` is the second hook to be executed in the request lifecycle. The
|
|
1387
|
+
preParsing` is the second hook to be executed in the request lifecycle. The
|
|
1388
|
+
previous hook was `onRequest`, the next hook will be `preValidation`.
|
|
1154
1389
|
|
|
1155
|
-
Notice: in the `preParsing` hook, request.body will always be null, because the
|
|
1390
|
+
Notice: in the `preParsing` hook, request.body will always be null, because the
|
|
1391
|
+
body parsing happens before the `preValidation` hook.
|
|
1156
1392
|
|
|
1157
|
-
Notice: you should also add `receivedEncodedLength` property to the returned
|
|
1393
|
+
Notice: you should also add `receivedEncodedLength` property to the returned
|
|
1394
|
+
stream. This property is used to correctly match the request payload with the
|
|
1395
|
+
`Content-Length` header value. Ideally, this property should be updated on each
|
|
1396
|
+
received chunk.
|
|
1158
1397
|
|
|
1159
1398
|
##### fastify.preValidationHookHandler<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>(request: [FastifyRequest][FastifyRequest], reply: [FastifyReply][FastifyReply], done: (err?: [FastifyError][FastifyError]) => void): Promise\<unknown\> | void
|
|
1160
1399
|
|
|
1161
|
-
[src](
|
|
1400
|
+
[src](https://github.com/fastify/fastify/blob/main/types/hooks.d.ts#L53)
|
|
1162
1401
|
|
|
1163
|
-
`preValidation` is the third hook to be executed in the request lifecycle. The
|
|
1402
|
+
`preValidation` is the third hook to be executed in the request lifecycle. The
|
|
1403
|
+
previous hook was `preParsing`, the next hook will be `preHandler`.
|
|
1164
1404
|
|
|
1165
1405
|
##### fastify.preHandlerHookHandler<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>(request: [FastifyRequest][FastifyRequest], reply: [FastifyReply][FastifyReply], done: (err?: [FastifyError][FastifyError]) => void): Promise\<unknown\> | void
|
|
1166
1406
|
|
|
1167
|
-
[src](
|
|
1407
|
+
[src](https://github.com/fastify/fastify/blob/main/types/hooks.d.ts#L70)
|
|
1168
1408
|
|
|
1169
|
-
`preHandler` is the fourth hook to be executed in the request lifecycle. The
|
|
1409
|
+
`preHandler` is the fourth hook to be executed in the request lifecycle. The
|
|
1410
|
+
previous hook was `preValidation`, the next hook will be `preSerialization`.
|
|
1170
1411
|
|
|
1171
1412
|
##### fastify.preSerializationHookHandler<PreSerializationPayload, [RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>(request: [FastifyRequest][FastifyRequest], reply: [FastifyReply][FastifyReply], payload: PreSerializationPayload, done: (err: [FastifyError][FastifyError] | null, res?: unknown) => void): Promise\<unknown\> | void
|
|
1172
1413
|
|
|
1173
|
-
[src](
|
|
1414
|
+
[src](https://github.com/fastify/fastify/blob/main/types/hooks.d.ts#L94)
|
|
1174
1415
|
|
|
1175
|
-
`preSerialization` is the fifth hook to be executed in the request lifecycle.
|
|
1416
|
+
`preSerialization` is the fifth hook to be executed in the request lifecycle.
|
|
1417
|
+
The previous hook was `preHandler`, the next hook will be `onSend`.
|
|
1176
1418
|
|
|
1177
|
-
Note: the hook is NOT called if the payload is a string, a Buffer, a stream or
|
|
1419
|
+
Note: the hook is NOT called if the payload is a string, a Buffer, a stream or
|
|
1420
|
+
null.
|
|
1178
1421
|
|
|
1179
1422
|
##### fastify.onSendHookHandler<OnSendPayload, [RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>(request: [FastifyRequest][FastifyRequest], reply: [FastifyReply][FastifyReply], payload: OnSendPayload, done: (err: [FastifyError][FastifyError] | null, res?: unknown) => void): Promise\<unknown\> | void
|
|
1180
1423
|
|
|
1181
|
-
[src](
|
|
1424
|
+
[src](https://github.com/fastify/fastify/blob/main/types/hooks.d.ts#L114)
|
|
1182
1425
|
|
|
1183
|
-
You can change the payload with the `onSend` hook. It is the sixth hook to be
|
|
1426
|
+
You can change the payload with the `onSend` hook. It is the sixth hook to be
|
|
1427
|
+
executed in the request lifecycle. The previous hook was `preSerialization`, the
|
|
1428
|
+
next hook will be `onResponse`.
|
|
1184
1429
|
|
|
1185
|
-
Note: If you change the payload, you may only change it to a string, a Buffer, a
|
|
1430
|
+
Note: If you change the payload, you may only change it to a string, a Buffer, a
|
|
1431
|
+
stream, or null.
|
|
1186
1432
|
|
|
1187
1433
|
##### fastify.onResponseHookHandler<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>(request: [FastifyRequest][FastifyRequest], reply: [FastifyReply][FastifyReply], done: (err?: [FastifyError][FastifyError]) => void): Promise\<unknown\> | void
|
|
1188
1434
|
|
|
1189
|
-
[src](
|
|
1435
|
+
[src](https://github.com/fastify/fastify/blob/main/types/hooks.d.ts#L134)
|
|
1190
1436
|
|
|
1191
|
-
`onResponse` is the seventh and last hook in the request hook lifecycle. The
|
|
1437
|
+
`onResponse` is the seventh and last hook in the request hook lifecycle. The
|
|
1438
|
+
previous hook was `onSend`, there is no next hook.
|
|
1192
1439
|
|
|
1193
|
-
The onResponse hook is executed when a response has been sent, so you will not
|
|
1440
|
+
The onResponse hook is executed when a response has been sent, so you will not
|
|
1441
|
+
be able to send more data to the client. It can however be useful for sending
|
|
1442
|
+
data to external services, for example to gather statistics.
|
|
1194
1443
|
|
|
1195
1444
|
##### fastify.onErrorHookHandler<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>(request: [FastifyRequest][FastifyRequest], reply: [FastifyReply][FastifyReply], error: [FastifyError][FastifyError], done: () => void): Promise\<unknown\> | void
|
|
1196
1445
|
|
|
1197
|
-
[src](
|
|
1446
|
+
[src](https://github.com/fastify/fastify/blob/main/types/hooks.d.ts#L154)
|
|
1198
1447
|
|
|
1199
|
-
This hook is useful if you need to do some custom error logging or add some
|
|
1448
|
+
This hook is useful if you need to do some custom error logging or add some
|
|
1449
|
+
specific header in case of error.
|
|
1200
1450
|
|
|
1201
|
-
It is not intended for changing the error, and calling reply.send will throw an
|
|
1451
|
+
It is not intended for changing the error, and calling reply.send will throw an
|
|
1452
|
+
exception.
|
|
1202
1453
|
|
|
1203
|
-
This hook will be executed only after the customErrorHandler has been executed,
|
|
1454
|
+
This hook will be executed only after the customErrorHandler has been executed,
|
|
1455
|
+
and only if the customErrorHandler sends an error back to the user (Note that
|
|
1456
|
+
the default customErrorHandler always sends the error back to the user).
|
|
1204
1457
|
|
|
1205
|
-
Notice: unlike the other hooks, pass an error to the done function is not
|
|
1458
|
+
Notice: unlike the other hooks, pass an error to the done function is not
|
|
1459
|
+
supported.
|
|
1206
1460
|
|
|
1207
1461
|
##### fastify.onRouteHookHandler<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [RequestGeneric][FastifyRequestGenericInterface], [ContextConfig][ContextConfigGeneric]>(opts: [RouteOptions][RouteOptions] & { path: string; prefix: string }): Promise\<unknown\> | void
|
|
1208
1462
|
|
|
1209
|
-
[src](
|
|
1463
|
+
[src](https://github.com/fastify/fastify/blob/main/types/hooks.d.ts#L174)
|
|
1210
1464
|
|
|
1211
|
-
Triggered when a new route is registered. Listeners are passed a routeOptions
|
|
1465
|
+
Triggered when a new route is registered. Listeners are passed a routeOptions
|
|
1466
|
+
object as the sole parameter. The interface is synchronous, and, as such, the
|
|
1467
|
+
listener does not get passed a callback
|
|
1212
1468
|
|
|
1213
1469
|
##### fastify.onRegisterHookHandler<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [Logger][LoggerGeneric]>(instance: [FastifyInstance][FastifyInstance], done: (err?: [FastifyError][FastifyError]) => void): Promise\<unknown\> | void
|
|
1214
1470
|
|
|
1215
|
-
[src](
|
|
1471
|
+
[src](https://github.com/fastify/fastify/blob/main/types/hooks.d.ts#L191)
|
|
1216
1472
|
|
|
1217
|
-
Triggered when a new plugin is registered and a new encapsulation context is
|
|
1473
|
+
Triggered when a new plugin is registered and a new encapsulation context is
|
|
1474
|
+
created. The hook will be executed before the registered code.
|
|
1218
1475
|
|
|
1219
|
-
This hook can be useful if you are developing a plugin that needs to know when a
|
|
1476
|
+
This hook can be useful if you are developing a plugin that needs to know when a
|
|
1477
|
+
plugin context is formed, and you want to operate in that specific context.
|
|
1220
1478
|
|
|
1221
1479
|
Note: This hook will not be called if a plugin is wrapped inside fastify-plugin.
|
|
1222
1480
|
|
|
1223
1481
|
##### fastify.onCloseHookHandler<[RawServer][RawServerGeneric], [RawRequest][RawRequestGeneric], [RawReply][RawReplyGeneric], [Logger][LoggerGeneric]>(instance: [FastifyInstance][FastifyInstance], done: (err?: [FastifyError][FastifyError]) => void): Promise\<unknown\> | void
|
|
1224
1482
|
|
|
1225
|
-
[src](
|
|
1483
|
+
[src](https://github.com/fastify/fastify/blob/main/types/hooks.d.ts#L206)
|
|
1226
1484
|
|
|
1227
|
-
Triggered when fastify.close() is invoked to stop the server. It is useful when
|
|
1485
|
+
Triggered when fastify.close() is invoked to stop the server. It is useful when
|
|
1486
|
+
plugins need a "shutdown" event, for example to close an open connection to a
|
|
1487
|
+
database.
|
|
1228
1488
|
|
|
1229
1489
|
|
|
1230
1490
|
<!-- Links -->
|
|
@@ -1247,7 +1507,7 @@ Triggered when fastify.close() is invoked to stop the server. It is useful when
|
|
|
1247
1507
|
[FastifyInstance]: #fastifyfastifyinstance
|
|
1248
1508
|
[FastifyLoggerOptions]: #fastifyfastifyloggeroptions
|
|
1249
1509
|
[ContextConfigGeneric]: #ContextConfigGeneric
|
|
1250
|
-
[FastifyPlugin]:
|
|
1510
|
+
[FastifyPlugin]: #fastifyfastifypluginoptions-rawserver-rawrequest-requestgeneric
|
|
1251
1511
|
[FastifyPluginCallback]: #fastifyfastifyplugincallbackoptions
|
|
1252
1512
|
[FastifyPluginAsync]: #fastifyfastifypluginasyncoptions
|
|
1253
1513
|
[FastifyPluginOptions]: #fastifyfastifypluginoptions
|