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
|
@@ -4,9 +4,10 @@
|
|
|
4
4
|
- [Reply](#reply)
|
|
5
5
|
- [Introduction](#introduction)
|
|
6
6
|
- [.code(statusCode)](#codestatuscode)
|
|
7
|
-
- [.statusCode](#
|
|
7
|
+
- [.statusCode](#statuscode)
|
|
8
8
|
- [.server](#server)
|
|
9
9
|
- [.header(key, value)](#headerkey-value)
|
|
10
|
+
- [set-cookie](#set-cookie)
|
|
10
11
|
- [.headers(object)](#headersobject)
|
|
11
12
|
- [.getHeader(key)](#getheaderkey)
|
|
12
13
|
- [.getHeaders()](#getheaders)
|
|
@@ -16,10 +17,10 @@
|
|
|
16
17
|
- [.callNotFound()](#callnotfound)
|
|
17
18
|
- [.getResponseTime()](#getresponsetime)
|
|
18
19
|
- [.type(contentType)](#typecontenttype)
|
|
19
|
-
- [.raw](#raw)
|
|
20
20
|
- [.serializer(func)](#serializerfunc)
|
|
21
|
+
- [.raw](#raw)
|
|
21
22
|
- [.sent](#sent)
|
|
22
|
-
- [.hijack](#hijack)
|
|
23
|
+
- [.hijack()](#hijack)
|
|
23
24
|
- [.send(data)](#senddata)
|
|
24
25
|
- [Objects](#objects)
|
|
25
26
|
- [Strings](#strings)
|
|
@@ -28,13 +29,13 @@
|
|
|
28
29
|
- [Errors](#errors)
|
|
29
30
|
- [Type of the final payload](#type-of-the-final-payload)
|
|
30
31
|
- [Async-Await and Promises](#async-await-and-promises)
|
|
31
|
-
- [.then](#
|
|
32
|
+
- [.then(fulfilled, rejected)](#thenfulfilled-rejected)
|
|
32
33
|
|
|
33
|
-
<a name="introduction"></a>
|
|
34
34
|
### Introduction
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
35
|
+
<a id="introduction"></a>
|
|
36
|
+
|
|
37
|
+
The second parameter of the handler function is `Reply`. Reply is a core Fastify
|
|
38
|
+
object that exposes the following functions and properties:
|
|
38
39
|
|
|
39
40
|
- `.code(statusCode)` - Sets the status code.
|
|
40
41
|
- `.status(statusCode)` - An alias for `.code(statusCode)`.
|
|
@@ -47,17 +48,26 @@ and properties:
|
|
|
47
48
|
- `.removeHeader(key)` - Remove the value of a previously set header.
|
|
48
49
|
- `.hasHeader(name)` - Determine if a header has been set.
|
|
49
50
|
- `.type(value)` - Sets the header `Content-Type`.
|
|
50
|
-
- `.redirect([code,] dest)` - Redirect to the specified url, the status code is
|
|
51
|
+
- `.redirect([code,] dest)` - Redirect to the specified url, the status code is
|
|
52
|
+
optional (default to `302`).
|
|
51
53
|
- `.callNotFound()` - Invokes the custom not found handler.
|
|
52
|
-
- `.serialize(payload)` - Serializes the specified payload using the default
|
|
54
|
+
- `.serialize(payload)` - Serializes the specified payload using the default
|
|
55
|
+
JSON serializer or using the custom serializer (if one is set) and returns the
|
|
56
|
+
serialized payload.
|
|
53
57
|
- `.serializer(function)` - Sets a custom serializer for the payload.
|
|
54
|
-
- `.send(payload)` - Sends the payload to the user, could be a plain text, a
|
|
55
|
-
|
|
56
|
-
- `.
|
|
57
|
-
|
|
58
|
+
- `.send(payload)` - Sends the payload to the user, could be a plain text, a
|
|
59
|
+
buffer, JSON, stream, or an Error object.
|
|
60
|
+
- `.sent` - A boolean value that you can use if you need to know if `send` has
|
|
61
|
+
already been called.
|
|
62
|
+
- `.raw` - The
|
|
63
|
+
[`http.ServerResponse`](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_class_http_serverresponse)
|
|
64
|
+
from Node core.
|
|
65
|
+
- `.res` *(deprecated, use `.raw` instead)* - The
|
|
66
|
+
[`http.ServerResponse`](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_class_http_serverresponse)
|
|
67
|
+
from Node core.
|
|
58
68
|
- `.log` - The logger instance of the incoming request.
|
|
59
69
|
- `.request` - The incoming request.
|
|
60
|
-
- `.context` - Access the [Request's context](Request.md
|
|
70
|
+
- `.context` - Access the [Request's context](./Request.md) property.
|
|
61
71
|
|
|
62
72
|
```js
|
|
63
73
|
fastify.get('/', options, function (request, reply) {
|
|
@@ -77,22 +87,27 @@ fastify.get('/', {config: {foo: 'bar'}}, function (request, reply) {
|
|
|
77
87
|
})
|
|
78
88
|
```
|
|
79
89
|
|
|
80
|
-
<a name="code"></a>
|
|
81
90
|
### .code(statusCode)
|
|
91
|
+
<a id="code"></a>
|
|
92
|
+
|
|
82
93
|
If not set via `reply.code`, the resulting `statusCode` will be `200`.
|
|
83
94
|
|
|
84
|
-
<a name="statusCode"></a>
|
|
85
95
|
### .statusCode
|
|
86
|
-
|
|
96
|
+
<a id="statusCode"></a>
|
|
97
|
+
|
|
98
|
+
This property reads and sets the HTTP status code. It is an alias for
|
|
99
|
+
`reply.code()` when used as a setter.
|
|
87
100
|
```js
|
|
88
101
|
if (reply.statusCode >= 299) {
|
|
89
102
|
reply.statusCode = 500
|
|
90
103
|
}
|
|
91
104
|
```
|
|
92
105
|
|
|
93
|
-
<a name="server"></a>
|
|
94
106
|
### .server
|
|
95
|
-
|
|
107
|
+
<a id="server"></a>
|
|
108
|
+
|
|
109
|
+
The Fastify server instance, scoped to the current [encapsulation
|
|
110
|
+
context](./Encapsulation.md).
|
|
96
111
|
|
|
97
112
|
```js
|
|
98
113
|
fastify.decorate('util', function util () {
|
|
@@ -104,16 +119,41 @@ fastify.get('/', async function (req, rep) {
|
|
|
104
119
|
})
|
|
105
120
|
```
|
|
106
121
|
|
|
107
|
-
<a name="header"></a>
|
|
108
122
|
### .header(key, value)
|
|
109
|
-
|
|
110
|
-
|
|
123
|
+
<a id="header"></a>
|
|
124
|
+
|
|
125
|
+
Sets a response header. If the value is omitted or undefined, it is coerced to
|
|
126
|
+
`''`.
|
|
127
|
+
|
|
128
|
+
For more information, see
|
|
129
|
+
[`http.ServerResponse#setHeader`](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_response_setheader_name_value).
|
|
130
|
+
|
|
131
|
+
- ### set-cookie
|
|
132
|
+
<a id="set-cookie"></a>
|
|
133
|
+
|
|
134
|
+
- When sending different values as a cookie with `set-cookie` as the key,
|
|
135
|
+
every value will be sent as a cookie instead of replacing the previous
|
|
136
|
+
value.
|
|
137
|
+
|
|
138
|
+
```js
|
|
139
|
+
reply.header('set-cookie', 'foo');
|
|
140
|
+
reply.header('set-cookie', 'bar');
|
|
141
|
+
```
|
|
142
|
+
- The browser will only consider the latest reference of a key for the
|
|
143
|
+
`set-cookie` header. This is done to avoid parsing the `set-cookie` header
|
|
144
|
+
when added to a reply and speeds up the serialization of the reply.
|
|
145
|
+
|
|
146
|
+
- To reset the `set-cookie` header, you need to make an explicit call to
|
|
147
|
+
`reply.removeHeader('set-cookie')`, read more about `.removeHeader(key)`
|
|
148
|
+
[here](#removeheaderkey).
|
|
149
|
+
|
|
111
150
|
|
|
112
|
-
For more information, see [`http.ServerResponse#setHeader`](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_response_setheader_name_value).
|
|
113
151
|
|
|
114
|
-
<a name="headers"></a>
|
|
115
152
|
### .headers(object)
|
|
116
|
-
|
|
153
|
+
<a id="headers"></a>
|
|
154
|
+
|
|
155
|
+
Sets all the keys of the object as response headers.
|
|
156
|
+
[`.header`](#headerkey-value) will be called under the hood.
|
|
117
157
|
```js
|
|
118
158
|
reply.headers({
|
|
119
159
|
'x-foo': 'foo',
|
|
@@ -121,18 +161,21 @@ reply.headers({
|
|
|
121
161
|
})
|
|
122
162
|
```
|
|
123
163
|
|
|
124
|
-
<a name="getHeader"></a>
|
|
125
164
|
### .getHeader(key)
|
|
165
|
+
<a id="getHeader"></a>
|
|
166
|
+
|
|
126
167
|
Retrieves the value of a previously set header.
|
|
127
168
|
```js
|
|
128
169
|
reply.header('x-foo', 'foo') // setHeader: key, value
|
|
129
170
|
reply.getHeader('x-foo') // 'foo'
|
|
130
171
|
```
|
|
131
172
|
|
|
132
|
-
<a name="getHeaders"></a>
|
|
133
173
|
### .getHeaders()
|
|
174
|
+
<a id="getHeaders"></a>
|
|
134
175
|
|
|
135
|
-
Gets a shallow copy of all current response headers, including those set via the
|
|
176
|
+
Gets a shallow copy of all current response headers, including those set via the
|
|
177
|
+
raw `http.ServerResponse`. Note that headers set via Fastify take precedence
|
|
178
|
+
over those set via `http.ServerResponse`.
|
|
136
179
|
|
|
137
180
|
```js
|
|
138
181
|
reply.header('x-foo', 'foo')
|
|
@@ -141,8 +184,8 @@ reply.raw.setHeader('x-foo', 'foo2')
|
|
|
141
184
|
reply.getHeaders() // { 'x-foo': 'foo', 'x-bar': 'bar' }
|
|
142
185
|
```
|
|
143
186
|
|
|
144
|
-
<a name="getHeader"></a>
|
|
145
187
|
### .removeHeader(key)
|
|
188
|
+
<a id="getHeader"></a>
|
|
146
189
|
|
|
147
190
|
Remove the value of a previously set header.
|
|
148
191
|
```js
|
|
@@ -151,20 +194,25 @@ reply.removeHeader('x-foo')
|
|
|
151
194
|
reply.getHeader('x-foo') // undefined
|
|
152
195
|
```
|
|
153
196
|
|
|
154
|
-
<a name="hasHeader"></a>
|
|
155
197
|
### .hasHeader(key)
|
|
198
|
+
<a id="hasHeader"></a>
|
|
199
|
+
|
|
156
200
|
Returns a boolean indicating if the specified header has been set.
|
|
157
201
|
|
|
158
|
-
<a name="redirect"></a>
|
|
159
202
|
### .redirect([code ,] dest)
|
|
160
|
-
|
|
203
|
+
<a id="redirect"></a>
|
|
204
|
+
|
|
205
|
+
Redirects a request to the specified URL, the status code is optional, default
|
|
206
|
+
to `302` (if status code is not already set by calling `code`).
|
|
161
207
|
|
|
162
|
-
Example (no `reply.code()` call) sets status code to `302` and redirects to
|
|
208
|
+
Example (no `reply.code()` call) sets status code to `302` and redirects to
|
|
209
|
+
`/home`
|
|
163
210
|
```js
|
|
164
211
|
reply.redirect('/home')
|
|
165
212
|
```
|
|
166
213
|
|
|
167
|
-
Example (no `reply.code()` call) sets status code to `303` and redirects to
|
|
214
|
+
Example (no `reply.code()` call) sets status code to `303` and redirects to
|
|
215
|
+
`/home`
|
|
168
216
|
```js
|
|
169
217
|
reply.redirect(303, '/home')
|
|
170
218
|
```
|
|
@@ -179,36 +227,47 @@ Example (`reply.code()` call) sets status code to `302` and redirects to `/home`
|
|
|
179
227
|
reply.code(303).redirect(302, '/home')
|
|
180
228
|
```
|
|
181
229
|
|
|
182
|
-
<a name="call-not-found"></a>
|
|
183
230
|
### .callNotFound()
|
|
184
|
-
|
|
231
|
+
<a id="call-not-found"></a>
|
|
232
|
+
|
|
233
|
+
Invokes the custom not found handler. Note that it will only call `preHandler`
|
|
234
|
+
hook specified in [`setNotFoundHandler`](./Server.md#set-not-found-handler).
|
|
185
235
|
|
|
186
236
|
```js
|
|
187
237
|
reply.callNotFound()
|
|
188
238
|
```
|
|
189
239
|
|
|
190
|
-
<a name="getResponseTime"></a>
|
|
191
240
|
### .getResponseTime()
|
|
192
|
-
|
|
241
|
+
<a id="getResponseTime"></a>
|
|
242
|
+
|
|
243
|
+
Invokes the custom response time getter to calculate the amount of time passed
|
|
244
|
+
since the request was started.
|
|
193
245
|
|
|
194
|
-
Note that unless this function is called in the [`onResponse`
|
|
246
|
+
Note that unless this function is called in the [`onResponse`
|
|
247
|
+
hook](./Hooks.md#onresponse) it will always return `0`.
|
|
195
248
|
|
|
196
249
|
```js
|
|
197
250
|
const milliseconds = reply.getResponseTime()
|
|
198
251
|
```
|
|
199
252
|
|
|
200
|
-
<a name="type"></a>
|
|
201
253
|
### .type(contentType)
|
|
202
|
-
|
|
203
|
-
|
|
254
|
+
<a id="type"></a>
|
|
255
|
+
|
|
256
|
+
Sets the content type for the response. This is a shortcut for
|
|
257
|
+
`reply.header('Content-Type', 'the/type')`.
|
|
204
258
|
|
|
205
259
|
```js
|
|
206
260
|
reply.type('text/html')
|
|
207
261
|
```
|
|
208
262
|
|
|
209
|
-
<a name="serializer"></a>
|
|
210
263
|
### .serializer(func)
|
|
211
|
-
|
|
264
|
+
<a id="serializer"></a>
|
|
265
|
+
|
|
266
|
+
`.send()` will by default JSON-serialize any value that is not one of: `Buffer`,
|
|
267
|
+
`stream`, `string`, `undefined`, `Error`. If you need to replace the default
|
|
268
|
+
serializer with a custom serializer for a particular request, you can do so with
|
|
269
|
+
the `.serializer()` utility. Be aware that if you are using a custom serializer,
|
|
270
|
+
you must set a custom `'Content-Type'` header.
|
|
212
271
|
|
|
213
272
|
```js
|
|
214
273
|
reply
|
|
@@ -216,7 +275,9 @@ reply
|
|
|
216
275
|
.serializer(protoBuf.serialize)
|
|
217
276
|
```
|
|
218
277
|
|
|
219
|
-
Note that you don't need to use this utility inside a `handler` because Buffers,
|
|
278
|
+
Note that you don't need to use this utility inside a `handler` because Buffers,
|
|
279
|
+
streams, and strings (unless a serializer is set) are considered to already be
|
|
280
|
+
serialized.
|
|
220
281
|
|
|
221
282
|
```js
|
|
222
283
|
reply
|
|
@@ -224,11 +285,16 @@ reply
|
|
|
224
285
|
.send(protoBuf.serialize(data))
|
|
225
286
|
```
|
|
226
287
|
|
|
227
|
-
See [`.send()`](#send) for more information on sending different types of
|
|
288
|
+
See [`.send()`](#send) for more information on sending different types of
|
|
289
|
+
values.
|
|
228
290
|
|
|
229
|
-
<a name="raw"></a>
|
|
230
291
|
### .raw
|
|
231
|
-
|
|
292
|
+
<a id="raw"></a>
|
|
293
|
+
|
|
294
|
+
This is the
|
|
295
|
+
[`http.ServerResponse`](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_class_http_serverresponse)
|
|
296
|
+
from Node core. Whilst you are using the Fastify `Reply` object, the use of
|
|
297
|
+
`Reply.raw` functions is at your own risk as you are skipping all the Fastify
|
|
232
298
|
logic of handling the HTTP response. e.g.:
|
|
233
299
|
|
|
234
300
|
```js
|
|
@@ -241,20 +307,20 @@ app.get('/cookie-2', (req, reply) => {
|
|
|
241
307
|
reply.raw.end()
|
|
242
308
|
})
|
|
243
309
|
```
|
|
244
|
-
Another example of the misuse of `Reply.raw` is explained in
|
|
310
|
+
Another example of the misuse of `Reply.raw` is explained in
|
|
311
|
+
[Reply](#getheaders).
|
|
245
312
|
|
|
246
|
-
<a name="sent"></a>
|
|
247
313
|
### .sent
|
|
314
|
+
<a id="sent"></a>
|
|
248
315
|
|
|
249
|
-
As the name suggests, `.sent` is a property to indicate if
|
|
250
|
-
|
|
316
|
+
As the name suggests, `.sent` is a property to indicate if a response has been
|
|
317
|
+
sent via `reply.send()`.
|
|
251
318
|
|
|
252
|
-
In case a route handler is defined as an async function or it
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
request and response. Moreover, hooks will not be invoked.
|
|
319
|
+
In case a route handler is defined as an async function or it returns a promise,
|
|
320
|
+
it is possible to set `reply.sent = true` to indicate that the automatic
|
|
321
|
+
invocation of `reply.send()` once the handler promise resolve should be skipped.
|
|
322
|
+
By setting `reply.sent = true`, an application claims full responsibility for
|
|
323
|
+
the low-level request and response. Moreover, hooks will not be invoked.
|
|
258
324
|
|
|
259
325
|
As an example:
|
|
260
326
|
|
|
@@ -269,39 +335,60 @@ app.get('/', (req, reply) => {
|
|
|
269
335
|
|
|
270
336
|
If the handler rejects, the error will be logged.
|
|
271
337
|
|
|
272
|
-
<a name="hijack"></a>
|
|
273
338
|
### .hijack()
|
|
274
|
-
|
|
339
|
+
<a id="hijack"></a>
|
|
340
|
+
|
|
341
|
+
Sometimes you might need to halt the execution of the normal request lifecycle
|
|
342
|
+
and handle sending the response manually.
|
|
275
343
|
|
|
276
|
-
To achieve this, Fastify provides the `reply.hijack()` method that can be called
|
|
344
|
+
To achieve this, Fastify provides the `reply.hijack()` method that can be called
|
|
345
|
+
during the request lifecycle (At any point before `reply.send()` is called), and
|
|
346
|
+
allows you to prevent Fastify from sending the response, and from running the
|
|
347
|
+
remaining hooks (and user handler if the reply was hijacked before).
|
|
277
348
|
|
|
278
|
-
NB (*): If `reply.raw` is used to send a response back to the user, `onResponse`
|
|
349
|
+
NB (*): If `reply.raw` is used to send a response back to the user, `onResponse`
|
|
350
|
+
hooks will still be executed
|
|
279
351
|
|
|
280
|
-
<a name="send"></a>
|
|
281
352
|
### .send(data)
|
|
282
|
-
|
|
353
|
+
<a id="send"></a>
|
|
354
|
+
|
|
355
|
+
As the name suggests, `.send()` is the function that sends the payload to the
|
|
356
|
+
end user.
|
|
283
357
|
|
|
284
|
-
<a name="send-object"></a>
|
|
285
358
|
#### Objects
|
|
286
|
-
|
|
359
|
+
<a id="send-object"></a>
|
|
360
|
+
|
|
361
|
+
As noted above, if you are sending JSON objects, `send` will serialize the
|
|
362
|
+
object with
|
|
363
|
+
[fast-json-stringify](https://www.npmjs.com/package/fast-json-stringify) if you
|
|
364
|
+
set an output schema, otherwise, `JSON.stringify()` will be used.
|
|
287
365
|
```js
|
|
288
366
|
fastify.get('/json', options, function (request, reply) {
|
|
289
367
|
reply.send({ hello: 'world' })
|
|
290
368
|
})
|
|
291
369
|
```
|
|
292
370
|
|
|
293
|
-
<a name="send-string"></a>
|
|
294
371
|
#### Strings
|
|
295
|
-
|
|
372
|
+
<a id="send-string"></a>
|
|
373
|
+
|
|
374
|
+
If you pass a string to `send` without a `Content-Type`, it will be sent as
|
|
375
|
+
`text/plain; charset=utf-8`. If you set the `Content-Type` header and pass a
|
|
376
|
+
string to `send`, it will be serialized with the custom serializer if one is
|
|
377
|
+
set, otherwise, it will be sent unmodified (unless the `Content-Type` header is
|
|
378
|
+
set to `application/json; charset=utf-8`, in which case it will be
|
|
379
|
+
JSON-serialized like an object — see the section above).
|
|
296
380
|
```js
|
|
297
381
|
fastify.get('/json', options, function (request, reply) {
|
|
298
382
|
reply.send('plain string')
|
|
299
383
|
})
|
|
300
384
|
```
|
|
301
385
|
|
|
302
|
-
<a name="send-streams"></a>
|
|
303
386
|
#### Streams
|
|
304
|
-
|
|
387
|
+
<a id="send-streams"></a>
|
|
388
|
+
|
|
389
|
+
*send* can also handle streams out of the box. If you are sending a stream and
|
|
390
|
+
you have not set a `'Content-Type'` header, *send* will set it at
|
|
391
|
+
`'application/octet-stream'`.
|
|
305
392
|
```js
|
|
306
393
|
fastify.get('/streams', function (request, reply) {
|
|
307
394
|
const fs = require('fs')
|
|
@@ -310,9 +397,11 @@ fastify.get('/streams', function (request, reply) {
|
|
|
310
397
|
})
|
|
311
398
|
```
|
|
312
399
|
|
|
313
|
-
<a name="send-buffers"></a>
|
|
314
400
|
#### Buffers
|
|
315
|
-
|
|
401
|
+
<a id="send-buffers"></a>
|
|
402
|
+
|
|
403
|
+
If you are sending a buffer and you have not set a `'Content-Type'` header,
|
|
404
|
+
*send* will set it to `'application/octet-stream'`.
|
|
316
405
|
```js
|
|
317
406
|
const fs = require('fs')
|
|
318
407
|
fastify.get('/streams', function (request, reply) {
|
|
@@ -322,9 +411,11 @@ fastify.get('/streams', function (request, reply) {
|
|
|
322
411
|
})
|
|
323
412
|
```
|
|
324
413
|
|
|
325
|
-
<a name="errors"></a>
|
|
326
414
|
#### Errors
|
|
327
|
-
|
|
415
|
+
<a id="errors"></a>
|
|
416
|
+
|
|
417
|
+
If you pass to *send* an object that is an instance of *Error*, Fastify will
|
|
418
|
+
automatically create an error structured as the following:
|
|
328
419
|
|
|
329
420
|
```js
|
|
330
421
|
{
|
|
@@ -335,10 +426,16 @@ If you pass to *send* an object that is an instance of *Error*, Fastify will aut
|
|
|
335
426
|
}
|
|
336
427
|
```
|
|
337
428
|
|
|
338
|
-
You can add custom properties to the Error object, such as `headers`, that will
|
|
339
|
-
|
|
429
|
+
You can add custom properties to the Error object, such as `headers`, that will
|
|
430
|
+
be used to enhance the HTTP response.
|
|
431
|
+
|
|
432
|
+
*Note: If you are passing an error to `send` and the statusCode is less than
|
|
433
|
+
400, Fastify will automatically set it at 500.*
|
|
340
434
|
|
|
341
|
-
Tip: you can simplify errors by using the
|
|
435
|
+
Tip: you can simplify errors by using the
|
|
436
|
+
[`http-errors`](https://npm.im/http-errors) module or
|
|
437
|
+
[`fastify-sensible`](https://github.com/fastify/fastify-sensible) plugin to
|
|
438
|
+
generate errors:
|
|
342
439
|
|
|
343
440
|
```js
|
|
344
441
|
fastify.get('/', function (request, reply) {
|
|
@@ -351,7 +448,8 @@ To customize the JSON error output you can do it by:
|
|
|
351
448
|
- setting a response JSON schema for the status code you need
|
|
352
449
|
- add the additional properties to the `Error` instance
|
|
353
450
|
|
|
354
|
-
Notice that if the returned status code is not in the response schema list, the
|
|
451
|
+
Notice that if the returned status code is not in the response schema list, the
|
|
452
|
+
default behaviour will be applied.
|
|
355
453
|
|
|
356
454
|
```js
|
|
357
455
|
fastify.get('/', {
|
|
@@ -376,7 +474,9 @@ fastify.get('/', {
|
|
|
376
474
|
})
|
|
377
475
|
```
|
|
378
476
|
|
|
379
|
-
If you want to customize error handling, check out
|
|
477
|
+
If you want to customize error handling, check out
|
|
478
|
+
[`setErrorHandler`](./Server.md#seterrorhandler) API.
|
|
479
|
+
|
|
380
480
|
*Note: you are responsible for logging when customizing the error handler*
|
|
381
481
|
|
|
382
482
|
API:
|
|
@@ -392,7 +492,8 @@ fastify.setErrorHandler(function (error, request, reply) {
|
|
|
392
492
|
})
|
|
393
493
|
```
|
|
394
494
|
|
|
395
|
-
The not found errors generated by the router will use the
|
|
495
|
+
The not found errors generated by the router will use the
|
|
496
|
+
[`setNotFoundHandler`](./Server.md#setnotfoundhandler)
|
|
396
497
|
|
|
397
498
|
API:
|
|
398
499
|
|
|
@@ -405,9 +506,12 @@ fastify.setNotFoundHandler(function (request, reply) {
|
|
|
405
506
|
})
|
|
406
507
|
```
|
|
407
508
|
|
|
408
|
-
<a name="payload-type"></a>
|
|
409
509
|
#### Type of the final payload
|
|
410
|
-
|
|
510
|
+
<a id="payload-type"></a>
|
|
511
|
+
|
|
512
|
+
The type of the sent payload (after serialization and going through any
|
|
513
|
+
[`onSend` hooks](./Hooks.md#onsend)) must be one of the following
|
|
514
|
+
types, otherwise, an error will be thrown:
|
|
411
515
|
|
|
412
516
|
- `string`
|
|
413
517
|
- `Buffer`
|
|
@@ -415,9 +519,11 @@ The type of the sent payload (after serialization and going through any [`onSend
|
|
|
415
519
|
- `undefined`
|
|
416
520
|
- `null`
|
|
417
521
|
|
|
418
|
-
<a name="async-await-promise"></a>
|
|
419
522
|
#### Async-Await and Promises
|
|
420
|
-
|
|
523
|
+
<a id="async-await-promise"></a>
|
|
524
|
+
|
|
525
|
+
Fastify natively handles promises and supports async-await.
|
|
526
|
+
|
|
421
527
|
*Note that in the following examples we are not using reply.send.*
|
|
422
528
|
```js
|
|
423
529
|
const delay = promisify(setTimeout)
|
|
@@ -432,7 +538,9 @@ fastify.get('/async-await', options, async function (request, reply) {
|
|
|
432
538
|
})
|
|
433
539
|
```
|
|
434
540
|
|
|
435
|
-
Rejected promises default to a `500` HTTP status code. Reject the promise, or
|
|
541
|
+
Rejected promises default to a `500` HTTP status code. Reject the promise, or
|
|
542
|
+
`throw` in an `async function`, with an object that has `statusCode` (or
|
|
543
|
+
`status`) and `message` properties to modify the reply.
|
|
436
544
|
|
|
437
545
|
```js
|
|
438
546
|
fastify.get('/teapot', async function (request, reply) {
|
|
@@ -448,22 +556,25 @@ fastify.get('/botnet', async function (request, reply) {
|
|
|
448
556
|
})
|
|
449
557
|
```
|
|
450
558
|
|
|
451
|
-
If you want to know more please review
|
|
559
|
+
If you want to know more please review
|
|
560
|
+
[Routes#async-await](./Routes.md#async-await).
|
|
452
561
|
|
|
453
|
-
<a name="then"></a>
|
|
454
562
|
### .then(fulfilled, rejected)
|
|
563
|
+
<a id="then"></a>
|
|
455
564
|
|
|
456
|
-
As the name suggests, a `Reply` object can be awaited upon, i.e. `await reply`
|
|
457
|
-
The `await` syntax calls the `reply.then()`.
|
|
565
|
+
As the name suggests, a `Reply` object can be awaited upon, i.e. `await reply`
|
|
566
|
+
will wait until the reply is sent. The `await` syntax calls the `reply.then()`.
|
|
458
567
|
|
|
459
568
|
`reply.then(fulfilled, rejected)` accepts two parameters:
|
|
460
569
|
|
|
461
570
|
- `fulfilled` will be called when a response has been fully sent,
|
|
462
|
-
- `rejected` will be called if the underlying stream had an error, e.g.
|
|
463
|
-
|
|
571
|
+
- `rejected` will be called if the underlying stream had an error, e.g. the
|
|
572
|
+
socket has been destroyed.
|
|
464
573
|
|
|
465
574
|
For more details, see:
|
|
466
575
|
|
|
467
|
-
- https://github.com/fastify/fastify/issues/1864 for the discussion about this
|
|
576
|
+
- https://github.com/fastify/fastify/issues/1864 for the discussion about this
|
|
577
|
+
feature
|
|
468
578
|
- https://promisesaplus.com/ for the definition of thenables
|
|
469
|
-
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
|
|
579
|
+
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
|
|
580
|
+
for the signature
|
|
@@ -1,35 +1,50 @@
|
|
|
1
1
|
<h1 align="center">Fastify</h1>
|
|
2
2
|
|
|
3
3
|
## Request
|
|
4
|
-
The first parameter of the handler function is `Request
|
|
4
|
+
The first parameter of the handler function is `Request`.
|
|
5
|
+
|
|
5
6
|
Request is a core Fastify object containing the following fields:
|
|
6
|
-
- `query` - the parsed querystring, its format is specified by
|
|
7
|
-
|
|
7
|
+
- `query` - the parsed querystring, its format is specified by
|
|
8
|
+
[`querystringParser`](./Server.md#querystringparser)
|
|
9
|
+
- `body` - the request payload, see [Content-Type
|
|
10
|
+
Parser](./ContentTypeParser.md) for details on what request payloads Fastify
|
|
11
|
+
natively parses and how to support other content types
|
|
8
12
|
- `params` - the params matching the URL
|
|
9
13
|
- [`headers`](#headers) - the headers getter and setter
|
|
10
14
|
- `raw` - the incoming HTTP request from Node core
|
|
11
|
-
- `req` *(deprecated, use `.raw` instead)* - the incoming HTTP request from Node
|
|
12
|
-
|
|
15
|
+
- `req` *(deprecated, use `.raw` instead)* - the incoming HTTP request from Node
|
|
16
|
+
core
|
|
17
|
+
- `server` - The Fastify server instance, scoped to the current [encapsulation
|
|
18
|
+
context](./Encapsulation.md)
|
|
13
19
|
- `id` - the request ID
|
|
14
20
|
- `log` - the logger instance of the incoming request
|
|
15
21
|
- `ip` - the IP address of the incoming request
|
|
16
|
-
- `ips` - an array of the IP addresses, ordered from closest to furthest, in the
|
|
17
|
-
-
|
|
22
|
+
- `ips` - an array of the IP addresses, ordered from closest to furthest, in the
|
|
23
|
+
`X-Forwarded-For` header of the incoming request (only when the
|
|
24
|
+
[`trustProxy`](./Server.md#factory-trust-proxy) option is enabled)
|
|
25
|
+
- `hostname` - the host of the incoming request (derived from `X-Forwarded-Host`
|
|
26
|
+
header when the [`trustProxy`](./Server.md#factory-trust-proxy) option is
|
|
27
|
+
enabled). For HTTP/2 compatibility it returns `:authority` if no host header
|
|
28
|
+
exists.
|
|
18
29
|
- `protocol` - the protocol of the incoming request (`https` or `http`)
|
|
19
30
|
- `method` - the method of the incoming request
|
|
20
31
|
- `url` - the URL of the incoming request
|
|
21
|
-
- `routerMethod` - the method defined for the router that is handling the
|
|
22
|
-
|
|
32
|
+
- `routerMethod` - the method defined for the router that is handling the
|
|
33
|
+
request
|
|
34
|
+
- `routerPath` - the path pattern defined for the router that is handling the
|
|
35
|
+
request
|
|
23
36
|
- `is404` - true if request is being handled by 404 handler, false if it is not
|
|
24
|
-
- `connection` - Deprecated, use `socket` instead. The underlying connection of
|
|
37
|
+
- `connection` - Deprecated, use `socket` instead. The underlying connection of
|
|
38
|
+
the incoming request.
|
|
25
39
|
- `socket` - the underlying connection of the incoming request
|
|
26
|
-
- `context` - A Fastify internal object. You should not use it directly or
|
|
27
|
-
|
|
40
|
+
- `context` - A Fastify internal object. You should not use it directly or
|
|
41
|
+
modify it. It is useful to access one special key:
|
|
42
|
+
- `context.config` - The route [`config`](./Routes.md#routes-config) object.
|
|
28
43
|
|
|
29
44
|
### Headers
|
|
30
45
|
|
|
31
|
-
The `request.headers` is a getter that returns an Object with the headers of the
|
|
32
|
-
You can set custom headers like this:
|
|
46
|
+
The `request.headers` is a getter that returns an Object with the headers of the
|
|
47
|
+
incoming request. You can set custom headers like this:
|
|
33
48
|
|
|
34
49
|
```js
|
|
35
50
|
request.headers = {
|
|
@@ -38,8 +53,9 @@ request.headers = {
|
|
|
38
53
|
}
|
|
39
54
|
```
|
|
40
55
|
|
|
41
|
-
This operation will add to the request headers the new values that can be read
|
|
42
|
-
Moreover, you can still access the standard
|
|
56
|
+
This operation will add to the request headers the new values that can be read
|
|
57
|
+
calling `request.headers.bar`. Moreover, you can still access the standard
|
|
58
|
+
request's headers with the `request.raw.headers` property.
|
|
43
59
|
|
|
44
60
|
```js
|
|
45
61
|
fastify.post('/:params', options, function (request, reply) {
|