본문 바로가기
BACKEND/Node.js+NestJS

Fastify 알아보기

by 드로니뚜벅이 2023. 11. 25.

fastify는 Express 처럼 Node.js 기반의 백엔드 프레임워크 중 하나입니다.

이름에서 짐작할 수 있듯이 Express보다 거의 두 배 이상 빠른 성능과 편리한 로깅 처리, 개발 편의성, 확장성 등을 가지고 있지만 Express가 너무 광범위하게 많이 사용하다 보니 사용층은 생각보다 넓지는 않은 것 같습니다.

 

특징

  • 고성능(High performant) - 초당 최대 30,000개의 요청을 처리할 수 있는 가장 빠른 웹 프레임워크 중 하나입니다.
  • 확장성(Extensible) - 후크, 플러그인 및 데코레이터를 통해 확장이 가능합니다.
  • 스키마 기반(Schema based) - JSON 스키마를 사용해 경로를 검증하고 출력을 직렬화할 수 있으며 이 스키마는 고성능으로 컴파일할 수 있습니다.
  • 로깅(Logging) - 로그는 비용이 많이 든 기능이지만 최고 로거로 꼽히는 피노를 통해 이 비용을 거의 없다고 볼 수 있습니다.
  • 개발자 친화적(Developer friendly) - 성능과 보안을 희생하지 않으면서 개발자 친화적으로 구축되었습니다.
  • TypeScript - TypeScript 타입 선언 파일을 유지하기 위해 지원을 강화하고 있습니다.

 

설치

$ npm install fastify

 

 

사용하기

1. 아래처럼 server.js 를 생성합니다.

// Import the framework and instantiate it
import Fastify from 'fastify'
const fastify = Fastify({
  logger: true
})

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

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

 

2. 서버를 실행합니다.

$ node server

 

3. 클라이언트에서 서버에 접속해 봅니다. (웹브라우저 URL 입력창 혹은 curl  사용)

$ curl http://localhost:3000

 

Request/Response Validation & Hooks

import Fastify from 'fastify'
const fastify = Fastify({
  logger: true
})

fastify.route({
  method: 'GET',
  url: '/',
  schema: {
    // request needs to have a querystring with a `name` parameter
    querystring: {
      type: 'object',
      properties: {
          name: { type: 'string'}
      },
      required: ['name'],
    },
    // 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' }
  }
})

try {
  await fastify.listen({ port: 3000 })
} catch (err) {
  fastify.log.error(err)
  process.exit(1)
}

 

 

타입스크립트 지원

import Fastify, { FastifyInstance, RouteShorthandOptions } from 'fastify'
import { Server, IncomingMessage, ServerResponse } from 'http'

const server: FastifyInstance = Fastify({})

const opts: RouteShorthandOptions = {
  schema: {
    response: {
      200: {
        type: 'object',
        properties: {
          pong: {
            type: 'string'
          }
        }
      }
    }
  }
}

server.get('/ping', opts, async (request, reply) => {
  return { pong: 'it worked!' }
})

const start = async () => {
  try {
    await server.listen({ port: 3000 })

    const address = server.server.address()
    const port = typeof address === 'string' ? address : address?.port

  } catch (err) {
    server.log.error(err)
    process.exit(1)
  }
}

start()

 

 

참고 사이트

 

 

 

'BACKEND > Node.js+NestJS' 카테고리의 다른 글

fnm install - fast node manager  (0) 2024.06.24
Windows NVM 설치하기(install)  (1) 2023.12.17
NestJS 알아보기  (0) 2023.11.25
Swagger 사용해 보기  (0) 2023.02.03
NVM (Node Version Manager) - 노드 버전 관리하기  (0) 2022.04.15