Fastify ist ein hocheffizientes Web-Framework mit geringem Overhead, das auf erstklassige Entwicklererfahrung und maximale Geschwindigkeit ausgelegt ist.
Erste Schritte
Einführung & Dokumentation
Fastify bietet herausragenden Durchsatz durch schema-basierte Kompilierung und eine modulare Plugin-Architektur.
- Fastify Source Code (github.com)
- Fastify Documentation (fastify.dev)
Hello World Beispiel
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
Routendeklaration
fastify.route({
method: 'GET',
url: '/',
schema: { ··· },
handler: (req, reply) => { ··· },
beforeHandler: (req, reply, done) => { ··· }
})
Kurzschreibweisen (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 Handler
fastify.get('/', options, async (req, reply) => {
return data
// or
reply.send(data)
})
Bei asynchronen Handlern können Sie die Nutzlast direkt zurückgeben oder reply.send(data) aufrufen.
Request & Reply
Request-Objekt
request.query
request.body
request.params
request.headers
request.req // Node.js core incoming request
request.log.info('hello')
See: Request.
Reply-Objekt
Antwort-Header
reply.code(404)
reply.header('Content-Type', 'text/html')
reply.type('text/html')
Weiterleitungen (Redirects)
reply.redirect('/foo')
reply.redirect(302, '/foo')
Daten senden
reply.send(payload)
reply.sent // → true|false
See: Reply.
JSON-Schema-Validierung
Schema definieren
const schema = {
querystring: {
name: { type: 'string' },
excitement: { type: 'integer' }
},
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
}
Schema an Route übergeben
fastify.get('/', { schema }, (req, reply) => {
···
})
Routen-Optionsobjekt
fastify.route({
method: 'GET',
url: '/',
schema,
handler: (req, reply) => { ··· }
})
Die Definition eines JSON-Schemas ermöglicht ultraschnelle Validierung und automatisierte Serialisierung.
See: Validation and Serialization.
Plugins
Funktion als Plugin registrieren
fastify.register(
require('./route'),
err => { if (err) throw err }
)
route.js
module.exports = (fastify, options, next) => {
fastify.get('/', (req, reply) => { ··· })
next()
}
See: Plugins.
Mehrere Plugins registrieren
fastify.register([
require('./another-route'),
require('./yet-another-route')
], opts, (err) => {
if (err) throw err
})
Routen-Präfixe
fastify.register(
require('./route'),
{ prefix: '/v1' }
)
Präfixe werden automatisch allen Routen vorangestellt, die im jeweiligen Plugin-Kontext deklariert sind.
fastify-plugin Helfer
const fp = require('fastify-plugin')
module.exports = fp((fastify, opts, next) => {
fastify.decorate('utility', () => {})
next()
}, '0.x')
Ermöglicht es Plugins, die Kapselungsgrenzen zu umgehen und Dekoratoren mit übergeordneten Scopes zu teilen.
Middleware & Templates
Middleware-Integration
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')())