Fastify — это высокоэффективный веб-фреймворк с минимальными накладными расходами, нацеленный на высочайшую скорость обработки и удобство разработки.
С чего начать
Введение и документация
Fastify обеспечивает потрясающую производительность благодаря компиляции схем и модульной архитектуре плагинов.
- Fastify Source Code (github.com)
- Fastify Documentation (fastify.dev)
Пример 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}`)
})
Маршрутизация (Routing)
Объявление маршрута
fastify.route({
method: 'GET',
url: '/',
schema: { ··· },
handler: (req, reply) => { ··· },
beforeHandler: (req, reply, done) => { ··· }
})
Краткие методы (Shorthand)
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)
Обработчики Async / Await
fastify.get('/', options, async (req, reply) => {
return data
// or
reply.send(data)
})
В асинхронных обработчиках можно просто возвращать полезную нагрузку или вызывать reply.send(data).
Запрос и Ответ (Request & Reply)
Объект Request
request.query
request.body
request.params
request.headers
request.req // Node.js core incoming request
request.log.info('hello')
See: Request.
Объект Reply
Заголовки ответа
reply.code(404)
reply.header('Content-Type', 'text/html')
reply.type('text/html')
Редиректы
reply.redirect('/foo')
reply.redirect(302, '/foo')
Отправка данных
reply.send(payload)
reply.sent // → true|false
See: Reply.
Валидация по JSON-схеме
Определение схемы
const schema = {
querystring: {
name: { type: 'string' },
excitement: { type: 'integer' }
},
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
}
Передача схемы в маршрут
fastify.get('/', { schema }, (req, reply) => {
···
})
Объект параметров маршрута
fastify.route({
method: 'GET',
url: '/',
schema,
handler: (req, reply) => { ··· }
})
Определение JSON-схемы ускоряет валидацию и обеспечивает автоматическую оптимизацию сериализации.
See: Validation and Serialization.
Система плагинов
Регистрация функции как плагина
fastify.register(
require('./route'),
err => { if (err) throw err }
)
route.js
module.exports = (fastify, options, next) => {
fastify.get('/', (req, reply) => { ··· })
next()
}
See: Plugins.
Регистрация нескольких плагинов
fastify.register([
require('./another-route'),
require('./yet-another-route')
], opts, (err) => {
if (err) throw err
})
Префиксы маршрутов
fastify.register(
require('./route'),
{ prefix: '/v1' }
)
Префиксы автоматически добавляются ко всем маршрутам, объявленным внутри этого плагина.
Утилита fastify-plugin
const fp = require('fastify-plugin')
module.exports = fp((fastify, opts, next) => {
fastify.decorate('utility', () => {})
next()
}, '0.x')
Позволяет плагинам обходить инкапсуляцию области видимости и делиться декораторами с родительскими контекстами.
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')())