クイックリファレンス

Fastify チートシート

Fastifyのクイックリファレンス:ルーティング、JSONスキーマバリデーション、Replyヘルパー、プラグイン構造、フック、ミドルウェア。

· 公開日

Fastifyは、優れた開発者体験と圧倒的なスループットの提供に特化した、高効率で低オーバーヘッドなWebフレームワークです。

はじめに

概要とドキュメント

Fastify は、スキーマベースのコンパイルと拡張性の高いプラグインアーキテクチャにより卓越したパフォーマンスを提供します。

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)

ルート宣言

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

ショートハンドメソッド

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 ハンドラー

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

非同期ハンドラーでは、データをそのまま return するか、reply.send(data) を呼び出します。

リクエストとリプライ (Request & Reply)

Request オブジェクト

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

See: Request.

Reply オブジェクト

レスポンスヘッダー

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

リダイレクト

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

データ送信

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

See: Reply.

JSONスキーマバリデーション

スキーマの定義

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

ルートへのスキーマ指定

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

ルートオプションオブジェクト

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

JSONスキーマを定義することで、高速な検証と自動シリアライズの高速化が実現されます。

See: Validation and Serialization.

プラグインシステム

関数のプラグイン登録

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

route.js

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

See: Plugins.

複数プラグインの一括登録

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

ルートプレフィックス

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

プレフィックスは、そのプラグインコンテキストで宣言されたすべてのルートに自動で付与されます。

fastify-plugin ヘルパー

const fp = require('fastify-plugin')

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

スコープのカプセル化をバイパスし、デコレータを親スコープ全体で共有可能にします。

ミドルウェアとテンプレート

ミドルウェア統合

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

関連テーマ