Referência rápida

Guia Rápido Fastify

Guia de referência rápida para Fastify: roteamento, validação de esquema JSON, helpers de reply, plugins, hooks e templates.

· Publicado

Fastify é um framework web eficiente e de baixo overhead focado em proporcionar uma experiência de desenvolvimento excepcional e altíssimo throughput.

Primeiros Passos

Introdução e Documentação

Fastify entrega desempenho excelente por meio de compilação baseada em esquemas e arquitetura modular de plugins.

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

Roteamento (Routing)

Declaração de rota

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)

Handlers Async / Await

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

Com handlers assíncronos, você pode simplesmente retornar os dados ou chamar reply.send(data).

Requisição e Resposta (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

Cabeçalhos de resposta

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

Redirecionamentos

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

Envio de dados

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

See: Reply.

Validação de esquema JSON

Definindo um esquema

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

Passando esquema para a rota

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

Objeto de opções da rota

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

Definir um esquema JSON permite validação ultrarrápida e aceleração automática de serialização.

See: Validation and Serialization.

Arquitetura de Plugins

Registrando uma função 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.

Registrando múltiplos plugins

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

Prefixos de rota

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

Prefixos serão anexados automaticamente a todas as rotas declaradas no contexto daquele plugin.

Utilitário fastify-plugin

const fp = require('fastify-plugin')

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

Permite que plugins ultrapassem o encapsulamento de escopo e compartilhem decoradores com escopos pais.

Middlewares e Templates

Integração 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')())

Temas relacionados