1
0
mirror of https://github.com/onkelbeh/cheatsheets.git synced 2026-08-16 05:54:53 +02:00
Files
cheatsheets/fastify.md
2017-09-21 21:37:13 +08:00

2.9 KiB

title, category, layout, updated, intro
title category layout updated intro
Fastify JavaScript libraries 2017/sheet 2017-09-21 [Fastify](https://github.com/fastify/fastify) lets you create HTTP servers in Node.js with good performance. This guide targets fastify v0.28.x.

Hello world

{: .-prime}

const fastify = require('fastify')()

fastify.get('/', (req, reply) => {
  reply.send({ hello: 'world' })
})

fastify.listen(3000, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})

Register

app.js

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

route.js

function (fastify, opts, next) {
  fastify.get('/', (req, reply) => {
    reply.send({ hello: 'world' })
  })
})

See: Register

Register with prefix

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

This prefixes all routes in that module.

Routes

Writing routes

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

Shorthand declarations

fastify.get(path, [options], handler)
fastify.head(···)
fastify.post(···)
fastify.put(···)
fastify.delete(···)
fastify.options(···)
fastify.patch(···)

Async/await

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

When using async functions, you can either return data or use reply.send.

Request/reply

Request

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

See: Request

Reply

Response headers

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

Redirects

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

Sending

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

See: Reply

JSON schema

Define a JSON schema

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

Pass it to the route

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

{: data-line="1"}

or (same as above)

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

{: data-line="4"}

By defining a JSON schema, you get validation and improved performance.

See: Validation and serialize