路由
Full declaration
fastify.route(options)
method
: 目前只支持'DELETE'
,'GET'
,'HEAD'
,'PATCH'
,'POST'
,'PUT'
和'OPTIONS'
。可以是一个数组。url
: 路由匹配的路径 (path
的别名).schema
: 一个包含请求和响应模式的对象。
需要符合 JSON Schema 的格式。body
: 验证请求体,'POST'
或者'PUT'
请求。querystring
: 验证查询字符串。可以是一个完成的 JSON Schema 对象(符合{type: "object", properties: {...}}
)或者没有type
和properties
属性,而只有查询字符串列表。params
: 验证params
response
: 过滤并生成响应的 schema ,将会提升 10-20% 的吞吐量。headers
: 验证请求头。
beforeHandler(request, reply, done)
:
在处理请求之前调用的函数,对处理用户认证很有帮助。handler(request, reply)
: 处理请求的函数。schemaCompiler(schema)
:schemaCompiler
是一个指定 schema 编译器的方法。(用来验证 body, params, headers, querystring)。默认的schemaCompiler
返回一个实现ajv
接口的编译器。 Fastify 在内部使用它以达到快速验证。
路由系统是根据 find-my-way 处理的, 所以你可以参考它的文档构建应用的路由。
Example:
fastify.route({
method: 'GET',
url: '/',
schema: {
querystring: {
name: { type: 'string' },
excitement: { type: 'integer' }
},
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
},
handler: function (request, reply) {
reply.send({ hello: 'world' })
}
})
fastify.route({
method: 'GET',
url: '/',
schema: { ... },
beforeHandler: function (request, reply, done) {
// 你的认证逻辑
done()
},
handler: function (request, reply) {
reply.send({ hello: 'world' })
}
})
Shorthand declaration
fastify 支持类似 Express/Restify
的路由语法:
fastify.get(path, [options], handler)
fastify.head(path, [options], handler)
fastify.post(path, [options], handler)
fastify.put(path, [options], handler)
fastify.delete(path, [options], handler)
fastify.options(path, [options], handler)
fastify.patch(path, [options], handler)
Example:
const opts = {
schema: {
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
}
}
fastify.get('/', opts, (req, reply) => {
reply.send({ hello: 'world' })
})
fastify.all(path, [options], handler)
将会响应所有的请求方式。
Async Await
使用 async/await
:
fastify.get('/', options, async function (request, reply) {
var data = await getData()
var processed = await processData(data)
return processed
})
可以看到,我们没有调用 reply.send
来返回数据给用户,而是使用 return
,当然你也可以使用 replay.send
:
fastify.get('/', options, async function (request, reply) {
var data = await getData()
var processed = await processData(data)
reply.send(processed)
})
警告:如果同时使用
return
和reply.send
,则第二个值将会被舍弃,如果该值不是undefined
的话,同时会触发警告日志。
路由前缀
有时我们会维护两套不同版本的api,一般我们都会手动的给所有的路由加上版本号前缀,例如:v1/user
。
Fastify 提供了快速而智能的方式来创建不同版本的相同的api,而无需手动更改所有路由名称:
// server.js
const fastify = require('fastify')()
fastify.register(require('./routes/v1/users'), { prefix: '/v1' })
fastify.register(require('./routes/v2/users'), { prefix: '/v2' })
fastify.listen(3000)
// routes/v1/users.js
module.exports = function (fastify, opts, next) {
fastify.get('/user', handler_v1)
next()
}
// routes/v2/users.js
module.exports = function (fastify, opts, next) {
fastify.get('/user', handler_v2)
next()
}
因为在编译时会自动处理前缀(这也意味着性能不会受到影响),所以Fastify不会抱怨两个不同的路由使用相同的名称。
现在客户端将可以访问以下路由:
/v1/user
/v2/user
可以根据需要执行多次,也支持嵌套 register
和路由参数。
请注意,如果使用 fastify-plugin
,此选项将无法正常工作。