本文根据 Devhints / Fastify 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2017-09-23。
入门
简介
Fastify 让您能够以高性能在 Node.js 中创建 HTTP 服务器。本指南针对的是 Fastify v0.28.x。
- Fastify 源代码 (github.com)
- 文档 (github.com)
Hello world
const fastify = require('fastify')()
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
fastify.listen(3000, err => {
if (err) throw err
const port = fastify.server.address().port
console.log(`server listening on ${port}`)
})
插件 (Plugins)
app.js
fastify.register(require('./route'))
route.js
function (fastify, opts, next) {
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
next()
})
将应用程序的功能组织成插件。插件本质上就是函数。
参见: 插件 (Plugins)
路由
编写路由
fastify.route({
method: 'GET',
url: '/',
schema: { ··· },
handler: (req, reply) => { ··· }
beforeHandler: (req, reply, done) => { ··· }
})
简写声明
fastify.get(path, [options], handler)
fastify.head(···)
fastify.post(···)
fastify.put(···)
fastify.delete(···)
fastify.options(···)
fastify.patch(···)
Async/await
fastify.get('/', options, async (req, reply) => {
return data
// or
reply.send(data)
})
使用异步函数(async functions)时,您可以…… return 数据,或者使用…… reply.send.
请求/响应 (Request/reply)
请求
request.query
request.body
request.params
request.headers
request.req // Node.js core
request.log.info('hello')
参见: 请求
响应 (Reply)
响应头 (Response headers)
reply.code(404)
reply.header('Content-Type', 'text/html')
reply.type('text/html')
重定向 (Redirects)
reply.redirect('/foo')
reply.redirect(302, '/foo')
发送 (Sending)
reply.send(payload)
reply.sent // → true|false
参见: 响应 (Reply)
JSON 模式 (Schema)
定义一个 JSON 模式
const schema = {
querystring: {
name: { type: 'string' },
excitement: { type: 'integer' }
},
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
}
将其(Pass 模式)应用到路由中
fastify.get('/', { schema }, (req, reply) => {
···
})
或者(与上述相同)
fastify.route({
method: 'GET',
url: '/',
schema,
handler: (req, reply) => { ··· }
})
通过定义 JSON 模式,您可以获得数据验证功能并提升性能。
参见: 验证与序列化
插件 (Plugins)
使用函数
fastify.register(
require('./route'),
err => { if (err) throw err }
)
route.js
module.exports = (fastify, options, next) => {
fastify.get('/', ···)
next()
}
参见: 注册 (Register)
多个
fastify.register([
require('./another-route'),
require('./yet-another-route')
], opts, (err) => {
if (err) throw err
})
您可以传入数组至 register().
使用前缀进行注册
fastify.register(
require('./route'),
{ prefix: '/v1' }
)
这会为该模块中的所有路由添加前缀。
Helmet
const helmet = require('fastify-helmet')
fastify.register(helmet)
参见: fastify-helmet
fastify-plugin
const fp = require('fastify-plugin')
module.exports = fp((fastify, opts, next) => {
// your plugin code
fastify.decorate('utility', () => {})
next()
}, '0.x')
允许您通过语义化版本号(semver)限制 Fastify 版本,且无需创建新的 Fastify 作用域。
参见: fastify-plugin
装饰器(Decorators)
中间件(Middleware)
中间件(Middleware)
fastify.use(require('cors')())
fastify.use(require('dns-prefetch-control')())
fastify.use(require('frameguard')())
fastify.use(require('hide-powered-by')())
fastify.use(require('hsts')())
fastify.use(require('ienoopen')())
fastify.use(require('x-xss-protection')())
兼容 Express 和 Restify 中间件。(请勿使用这些中间件,它们的功能已被 fastify-helmet.)
参见: 中间件
模板渲染
point-of-view
const fastify = require('fastify')()
fastify.register(require('point-of-view'), {
engine: {
ejs: require('ejs')
}
})
fastify.get('/', (req, reply) => {
reply.view('/templates/index.ejs', { text: 'text' })
})
支持 ejs, pug, handlebars 以及 marko.
参见: point-of-view
选项
fastify.register(require('point-of-view'), {
engine: {
ejs: require('ejs')
},
templates: '/templates',
options: {}
})
templates 允许您更新模板文件夹。 options 是传递给模板引擎的选项。