UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【Fastify】Fastifyとは

FastifyというWebフレームワークを知ったので調べた

www.fastify.io

Fastify は、HapiとExpress にインスパイアされて開発されたWeb フレームワーク

最小限のオーバーヘッドと強力なプラグインアーキテクチャで最高の開発者体験を提供することに重点を置いたということで、めちゃめちゃ高速らしい

ドキュメントにある特徴

  • 高いパフォーマンス:1 秒あたり最大 30,000 のリクエストを処理できる
  • 拡張可能: Fastify は、hooks、plugin、およびdecoratorを介して拡張可能
  • スキーマベース:任意ではあるがルートのバリデーションと出力のシリアライズJSONスキーマを使用すること推奨していて、JSON スキーマを使用するとFastify は内部でスキーマを高パフォーマンス関数でコンパイルする
  • ロギング:Pinoを選択している
  • TypeScript対応

インストールしてとりあえず、アプリを作ってみた

// Require the framework and instantiate it
const fastify = require('fastify')({ logger: true })

// Declare a route
fastify.get('/', async (request, reply) => {
  return { hello: 'world' }
})

// Run the server!
const start = async () => {
  try {
    await fastify.listen({ port: 3000 })
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

expressに書き方は似ている

入力と出力のバリデーションをJSONスキーマにするというのは以下のような感じ

const fastify = require('fastify')({ logger: true })

fastify.route({
  method: 'GET',
  url: '/',
  schema: {
    // request needs to have a querystring with a `name` parameter
    querystring: {
      page: { type: 'number' }
    },
    // the response needs to be an object with an `hello` property of type 'string'
    response: {
      200: {
        type: 'object',
        properties: {
          hello: { type: 'string' }
        }
      }
    }
  },
  // this function is executed for every request before the handler is executed
  preHandler: async (request, reply) => {
    // E.g. check authentication
  },
  handler: async (request, reply) => {
    return { hello: 'world' }
  }
})

const start = async () => {
  try {
    await fastify.listen({ port: 3000 })
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

この場合、リクエストにはpageというキーをもったパラメータにはnumberがくることを期待しているので、page=aaaというクエリパラメータにした場合はエラーになる

バリデーターの実態はAjvらしく、オプションなどはそちらを見ると良いみたい

API 定義書をswaggerで作っている場合は、そこから肩定義とかバリデーションとかが生成されるのが正義だと思うので、このフレームワークはそれが実現できてよさそう

他参考

API仕様書をバリデーターと型と同期させて作る | blog.ojisan.io