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