Szybka pomoc

Ściągawka Fastify

Szybki przewodnik po Fastify: routing, walidacja schematów JSON, pomocniki reply, architektura wtyczek, hooki i middleware.

· Opublikowano

Fastify to wysoce wydajny framework internetowy o minimalnym narzucie, skupiony na komforcie programisty i maksymalnej przepustowości.

Pierwsze kroki

Wprowadzenie i Dokumentacja

Fastify zapewnia znakomitą wydajność dzięki kompilacji opartej na schematach i modułowej architekturze wtyczek.

Przykład 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

Deklaracja trasy

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

Metody skrótowe (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)

Handlery Async / Await

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

W asynchronicznych handlerach możesz po prostu zwrócić dane lub wywołać reply.send(data).

Żądanie i Odpowiedź (Request & Reply)

Obiekt Request

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

See: Request.

Obiekt Reply

Nagłówki odpowiedzi

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

Przekierowania

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

Wysyłanie danych

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

See: Reply.

Walidacja schematów JSON

Definiowanie schematu

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

Przekazanie schematu do trasy

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

Obiekt opcji trasy

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

Zdefiniowanie schematu JSON umożliwia błyskawiczną walidację oraz automatyczne przyspieszenie serializacji.

See: Validation and Serialization.

Architektura wtyczek (Plugins)

Rejestracja funkcji jako wtyczki

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

route.js

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

See: Plugins.

Rejestracja wielu wtyczek

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

Prefiksy tras

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

Prefiksy będą automatycznie dodawane do wszystkich tras zadeklarowanych w kontekście danej wtyczki.

Narzędzie fastify-plugin

const fp = require('fastify-plugin')

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

Pozwala wtyczkom ominąć enkapsulację zasięgu i współdzielić dekoratory z nadrzędnymi zasięgami.

Middleware i Szablony

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

Powiązane tematy