OSDN Git Service

Regular updates
[twpd/master.git] / fastify.md
1 ---
2 title: Fastify
3 category: JavaScript libraries
4 layout: 2017/sheet
5 updated: 2017-09-23
6 ---
7
8 ## Getting started
9
10 ### Introduction
11 {: .-intro}
12
13 [Fastify](https://github.com/fastify/fastify) lets you create HTTP servers in Node.js with good performance. This guide targets fastify v0.28.x.
14
15 - [Fastify source code](https://github.com/fastify/fastify) _(github.com)_
16 - [Documentation](https://github.com/fastify/fastify#documentation) _(github.com)_
17
18 ### Hello world
19 {: .-prime}
20
21 ```js
22 const fastify = require('fastify')()
23
24 fastify.get('/', (req, reply) => {
25   reply.send({ hello: 'world' })
26 })
27
28 fastify.listen(3000, err => {
29   if (err) throw err
30   const port = fastify.server.address().port
31   console.log(`server listening on ${port}`)
32 })
33 ```
34
35 ### Plugins
36
37 #### app.js
38
39 ```js
40 fastify.register(require('./route'))
41 ```
42
43 #### route.js
44
45 ```js
46 function (fastify, opts, next) {
47   fastify.get('/', (req, reply) => {
48     reply.send({ hello: 'world' })
49   })
50
51   next()
52 })
53 ```
54
55 Compose your app functionality into plugins. Plugins are simply functions.
56
57 See: [Plugins](https://github.com/fastify/fastify/blob/master/docs/Plugins.md)
58
59 ## Routes
60
61 ### Writing routes
62
63 ```js
64 fastify.route({
65   method: 'GET',
66   url: '/',
67   schema: { ··· },
68   handler: (req, reply) => { ··· }
69   beforeHandler: (req, reply, done) => { ··· }
70 })
71 ```
72
73 ### Shorthand declarations
74
75 ```js
76 fastify.get(path, [options], handler)
77 fastify.head(···)
78 fastify.post(···)
79 fastify.put(···)
80 fastify.delete(···)
81 fastify.options(···)
82 fastify.patch(···)
83 ```
84
85 ### Async/await
86
87 ```js
88 fastify.get('/', options, async (req, reply) => {
89   return data
90   // or
91   reply.send(data)
92 })
93 ```
94
95 When using async functions, you can either `return` data or use `reply.send`.
96
97 Request/reply
98 -------------
99
100 ### Request
101
102 ```js
103 request.query
104 request.body
105 request.params
106 request.headers
107 request.req  // Node.js core
108 request.log.info('hello')
109 ```
110
111 See: [Request](https://github.com/fastify/fastify/blob/master/docs/Request.md)
112
113 ### Reply
114
115 #### Response headers
116
117 ```js
118 reply.code(404)
119 reply.header('Content-Type', 'text/html')
120 reply.type('text/html')
121 ```
122
123 #### Redirects
124
125 ```js
126 reply.redirect('/foo')
127 reply.redirect(302, '/foo')
128 ```
129
130 #### Sending
131
132 ```js
133 reply.send(payload)
134 reply.sent // → true|false
135 ```
136
137 See: [Reply](https://github.com/fastify/fastify/blob/master/docs/Reply.md)
138
139 ### JSON schema
140
141 #### Define a JSON schema
142
143 ```js
144 const schema = {
145   querystring: {
146     name: { type: 'string' },
147     excitement: { type: 'integer' }
148   },
149   response: {
150     200: {
151       type: 'object',
152       properties: {
153         hello: { type: 'string' }
154       }
155     }
156   }
157 }
158 ```
159
160 #### Pass it to the route
161
162 ```js
163 fastify.get('/', { schema }, (req, reply) => {
164   ···
165 })
166 ```
167 {: data-line="1"}
168
169 #### or (same as above)
170
171 ```js
172 fastify.route({
173   method: 'GET',
174   url: '/',
175   schema,
176   handler: (req, reply) => { ··· }
177 })
178 ```
179 {: data-line="4"}
180
181 By defining a JSON schema, you get validation and improved performance.
182
183 See: [Validation and serialization](https://github.com/fastify/fastify/blob/master/docs/Validation-and-Serialization.md)
184
185 Plugins
186 -------
187
188 ### With function
189
190 ```js
191 fastify.register(
192   require('./route'),
193   err => { if (err) throw err }
194 )
195 ```
196 {: data-line="3"}
197
198 #### route.js
199
200 ```js
201 module.exports = (fastify, options, next) => {
202   fastify.get('/', ···)
203   next()
204 }
205 ```
206
207
208 See: [Register](https://github.com/fastify/fastify/blob/master/docs/Getting-Started.md#register)
209
210 ### Multiple
211
212 ```js
213 fastify.register([
214   require('./another-route'),
215   require('./yet-another-route')
216 ], opts, (err) => {
217   if (err) throw err
218 })
219 ```
220
221 You can pass arrays to `register()`.
222
223 ### Register with prefix
224
225 ```js
226 fastify.register(
227   require('./route'),
228   { prefix: '/v1' }
229 )
230 ```
231
232 This prefixes all routes in that module.
233
234 ### Helmet
235
236 ```js
237 const helmet = require('fastify-helmet')
238
239 fastify.register(helmet)
240 ```
241
242 See: [fastify-helmet](https://github.com/fastify/fastify-helmet)
243
244 ### fastify-plugin
245
246 ```js
247 const fp = require('fastify-plugin')
248
249 module.exports = fp((fastify, opts, next) => {
250   // your plugin code
251   fastify.decorate('utility', () => {})
252
253   next()
254 }, '0.x')
255 ```
256
257 Allows you to limit Fastify versions via semver, and allows you not make a new Fastify scope.
258
259 See: [fastify-plugin](https://github.com/fastify/fastify-plugin)
260
261 ### Decorators
262
263 Middleware
264 ----------
265
266 ### Middleware
267
268 ```js
269 fastify.use(require('cors')())
270 fastify.use(require('dns-prefetch-control')())
271 fastify.use(require('frameguard')())
272 fastify.use(require('hide-powered-by')())
273 fastify.use(require('hsts')())
274 fastify.use(require('ienoopen')())
275 fastify.use(require('x-xss-protection')())
276 ```
277
278 Compatible with Express and Restify middlewares. (Don't use these middleware, these are covered by [fastify-helmet](https://github.com/fastify/fastify-helmet).)
279
280 See: [Middlewares](https://github.com/fastify/fastify/blob/master/docs/Middleware.md)
281
282 Template rendering
283 ------------------
284
285 ### point-of-view
286
287 ```js
288 const fastify = require('fastify')()
289
290 fastify.register(require('point-of-view'), {
291   engine: {
292     ejs: require('ejs')
293   }
294 })
295 ```
296 {: data-line="3"}
297
298 ```js
299 fastify.get('/', (req, reply) => {
300   reply.view('/templates/index.ejs', { text: 'text' })
301 })
302 ```
303 {: data-line="2"}
304
305 Support `ejs`, `pug`, `handlebars` and `marko`.
306
307 See: [point-of-view](https://github.com/fastify/point-of-view)
308
309 ### Options
310
311 ```js
312 fastify.register(require('point-of-view'), {
313   engine: {
314     ejs: require('ejs')
315   },
316   templates: '/templates',
317   options: {}
318 })
319 ```
320
321 `templates` lets you update the templates folder. `options` are options passed onto the template engines.