Fastify è un framework web efficiente ea bassissimo overhead, progettato per offrire la migliore esperienza di sviluppo e throughput elevatissimo.
Primi Passi
Introduzione e Documentazione
Fastify offre prestazioni straordinarie grazie alla compilazione basata su schema ea un'architettura modulare di plugin.
- Fastify Source Code (github.com)
- Fastify Documentation (fastify.dev)
Esempio 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
Dichiarazione delle rotte
fastify.route({
method: 'GET',
url: '/',
schema: { ··· },
handler: (req, reply) => { ··· },
beforeHandler: (req, reply, done) => { ··· }
})
Metodi scorciatoia (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)
Gestori Async / Await
fastify.get('/', options, async (req, reply) => {
return data
// or
reply.send(data)
})
Con i gestori asincroni puoi semplicemente restituire i dati o invocare reply.send(data).
Richiesta e Risposta (Request & Reply)
Oggetto Request
request.query
request.body
request.params
request.headers
request.req // Node.js core incoming request
request.log.info('hello')
See: Request.
Oggetto Reply
Header di risposta
reply.code(404)
reply.header('Content-Type', 'text/html')
reply.type('text/html')
Reindirizzamenti
reply.redirect('/foo')
reply.redirect(302, '/foo')
Invio dati
reply.send(payload)
reply.sent // → true|false
See: Reply.
Validazione schema JSON
Definizione dello schema
const schema = {
querystring: {
name: { type: 'string' },
excitement: { type: 'integer' }
},
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
}
Passaggio dello schema alla rotta
fastify.get('/', { schema }, (req, reply) => {
···
})
Oggetto opzioni rotta
fastify.route({
method: 'GET',
url: '/',
schema,
handler: (req, reply) => { ··· }
})
La definizione di uno schema JSON abilita una validazione ultraveloce e una serializzazione automatica ottimizzata.
See: Validation and Serialization.
Architettura dei Plugin
Registrazione di una funzione come plugin
fastify.register(
require('./route'),
err => { if (err) throw err }
)
route.js
module.exports = (fastify, options, next) => {
fastify.get('/', (req, reply) => { ··· })
next()
}
See: Plugins.
Registrazione di più plugin
fastify.register([
require('./another-route'),
require('./yet-another-route')
], opts, (err) => {
if (err) throw err
})
Prefissi delle rotte
fastify.register(
require('./route'),
{ prefix: '/v1' }
)
I prefissi verranno anteposti automaticamente a tutte le rotte definite nel contesto del plugin.
Utility fastify-plugin
const fp = require('fastify-plugin')
module.exports = fp((fastify, opts, next) => {
fastify.decorate('utility', () => {})
next()
}, '0.x')
Consente ai plugin di oltrepassare l'incapsulamento di ambito e condividere decoratori con gli ambiti superiori.
Middleware e Template
Integrazione dei 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')())