Fastify es un framework web eficiente y de baja sobrecarga centrado en ofrecer la mejor experiencia de desarrollo y máxima velocidad de procesamiento.
Primeros Pasos
Introducción y Documentación
Fastify ofrece un rendimiento sobresaliente mediante compilación basada en esquemas y una arquitectura modular de plugins.
- Fastify Source Code (github.com)
- Fastify Documentation (fastify.dev)
Ejemplo Hola Mundo
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}`)
})
Enrutamiento (Routing)
Declaración de ruta completa
fastify.route({
method: 'GET',
url: '/',
schema: { ··· },
handler: (req, reply) => { ··· },
beforeHandler: (req, reply, done) => { ··· }
})
Métodos abreviados (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)
Controladores Async / Await
fastify.get('/', options, async (req, reply) => {
return data
// or
reply.send(data)
})
Con funciones asíncronas, puedes simplemente retornar la carga útil o invocar reply.send(data).
Petición y Respuesta (Request & Reply)
Objeto Request
request.query
request.body
request.params
request.headers
request.req // Node.js core incoming request
request.log.info('hello')
See: Request.
Objeto Reply
Cabeceras de respuesta
reply.code(404)
reply.header('Content-Type', 'text/html')
reply.type('text/html')
Redirecciones
reply.redirect('/foo')
reply.redirect(302, '/foo')
Envío de datos
reply.send(payload)
reply.sent // → true|false
See: Reply.
Validación de esquemas JSON
Definir un esquema
const schema = {
querystring: {
name: { type: 'string' },
excitement: { type: 'integer' }
},
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
}
Pasar esquema a la ruta
fastify.get('/', { schema }, (req, reply) => {
···
})
Objeto de opciones de ruta
fastify.route({
method: 'GET',
url: '/',
schema,
handler: (req, reply) => { ··· }
})
Definir un esquema JSON habilita validación ultrarrápida y serialización optimizada automática.
See: Validation and Serialization.
Plugins
Registrar una función como plugin
fastify.register(
require('./route'),
err => { if (err) throw err }
)
route.js
module.exports = (fastify, options, next) => {
fastify.get('/', (req, reply) => { ··· })
next()
}
See: Plugins.
Registrar múltiples plugins
fastify.register([
require('./another-route'),
require('./yet-another-route')
], opts, (err) => {
if (err) throw err
})
Prefijos de ruta
fastify.register(
require('./route'),
{ prefix: '/v1' }
)
Los prefijos se antepondrán automáticamente a todas las rutas declaradas en el contexto de ese plugin.
Utilidad fastify-plugin
const fp = require('fastify-plugin')
module.exports = fp((fastify, opts, next) => {
fastify.decorate('utility', () => {})
next()
}, '0.x')
Permite a los plugins evitar el encapsulamiento de ámbito y compartir decoradores con ámbitos superiores.
Middleware y Plantillas
Integración de 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')())