Referință rapidă

Cheat Sheet Fastify

Ghid de referință rapidă pentru Fastify: rutare, validare scheme JSON, reply helpers, arhitectura plugin-urilor, hooks și middleware.

· Publicat

Fastify este un framework web eficient și cu overhead redus, concentrat pe furnizarea unei experiențe de dezvoltare optime și viteză maximă.

Primii Pași

Introducere și Documentație

Fastify oferă performanțe deosebite datorită compilării bazate pe scheme și unei arhitecturi modulare de plugin-uri.

Exemplu 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}`)
})

Rutare (Routing)

Declararea rutelor

fastify.route({
  method: 'GET',
  url: '/',
  schema: { ··· },
  handler: (req, reply) => { ··· },
  beforeHandler: (req, reply, done) => { ··· }
})

Metode scurte (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)

Handlere Async / Await

fastify.get('/', options, async (req, reply) => {
  return data
  // or
  reply.send(data)
})

În handlere asincrone, puteți pur și simplu returna datele sau apela reply.send(data).

Cerere și Răspuns (Request & Reply)

Obiectul Request

request.query
request.body
request.params
request.headers
request.req  // Node.js core incoming request
request.log.info('hello')

See: Request.

Obiectul Reply

Antete de răspuns

reply.code(404)
reply.header('Content-Type', 'text/html')
reply.type('text/html')

Redirecționări

reply.redirect('/foo')
reply.redirect(302, '/foo')

Trimiterea datelor

reply.send(payload)
reply.sent // → true|false

See: Reply.

Validare schemă JSON

Definirea unei scheme

const schema = {
  querystring: {
    name: { type: 'string' },
    excitement: { type: 'integer' }
  },
  response: {
    200: {
      type: 'object',
      properties: {
        hello: { type: 'string' }
      }
    }
  }
}

Transmiterea schemei către rută

fastify.get('/', { schema }, (req, reply) => {
  ···
})

Obiectul de opțiuni al rutei

fastify.route({
  method: 'GET',
  url: '/',
  schema,
  handler: (req, reply) => { ··· }
})

Definirea unei scheme JSON permite validare ultra-rapidă și serializare accelerată automată.

See: Validation and Serialization.

Arhitectura Plugin-urilor

Înregistrarea unei funcții ca plugin

fastify.register(
  require('./route'),
  err => { if (err) throw err }
)

route.js

module.exports = (fastify, options, next) => {
  fastify.get('/', (req, reply) => { ··· })
  next()
}

See: Plugins.

Înregistrarea mai multor plugin-uri

fastify.register([
  require('./another-route'),
  require('./yet-another-route')
], opts, (err) => {
  if (err) throw err
})

Prefixe de rută

fastify.register(
  require('./route'),
  { prefix: '/v1' }
)

Prefixele vor fi adăugate automat tuturor rutelor declarate în contextul acelui plugin.

Utilitarul fastify-plugin

const fp = require('fastify-plugin')

module.exports = fp((fastify, opts, next) => {
  fastify.decorate('utility', () => {})
  next()
}, '0.x')

Permite plugin-urilor să evite încapsularea și să partajeze decoratori cu scope-urile părinte.

Middleware și Șabloane

Integrare 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')())

Subiecte conexe