Node.js framework ‘fastify’
Why
효율적인 서버는 낮은 비용으로 높은 응답성을 보여 사용자 경험을 향상시켜야 한다. 이를 위해서는 보안성을 유지하고 개발자의 개발에 불편함을 주지 않으면서도 수많은 사용자들의 요청을 효과적으로 처리해줄 필요가 있다.
fastify는 최소한의 오버헤드와 강력한 플러그인 아키텍처로 최고의 개발 경험을 제공하는데에 초점을 맞춘 웹 프레임워크이다.Hapi와 Express를 참고해 개발되었으며 이름처럼 현재 가장 빠른 웹 프레임워크 중 하나이다.
Who is using Fastify?
Fastify는 현재 많은 단체들과 제품들의 생태계에서 사용되고 있다.
다음과 같은 단체들에서 fastify를 사용중이며 그 외에도 추가적으로 fastify를 사용하는 단체들도 다수 존재한다.
Quick start
NPM모듈을 사용해 fastify를 설치할 수 있다.
$ npm install fastify
이후에는 server.js 라는 파일을 생성하고 다음 코드를 작성한다.
// Require the framework and instantiate it
const fastify = require('fastify')() // Declare a route
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
}) // Run the server!
const start = async () => {
try {
await fastify.listen(3000)
fastify.log.info(`server listening on ${fastify.server.address().port}`)
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
위 코드는 async function을 사용했다. async function은 함수 내에서 await를 사용할 수 있는 함수로, await 뒤에 호출되는 promise값이 결정될 때까지 대기한다.
마지막으로 서버를 실행시킨다:
$ node server
서버가 실행되면 curl명령어나 브라우저를 통해 localhost:3000에 접속해 본다.
$ curl http://localhost:3000
그러면 {"hello":"world"}라는 결과를 리턴해준 것을 확인할 수 있다.
현재 서버를 실행하면
fastify.log.info(`server listening on ${fastify.server.address().port}`)
부분에 따라 로그가 찍혀야 한다고 생각할 수 있으나 막상 서버를 실행시켜보면 해당 로그가 보이지 않는다. 로그를 출력하기 위해서는 fastify의 logger를 true값으로 설정해주어야 한다.
const fastify = require('fastify')({
logger: true
})
Request/Response validation and hooks
fastify는 JSON타입의 입출력 유효성 검사나 핸들러의 실행 이전에 특정 작업을 수행하는 것도 가능하다.
const fastify = require('fastify')()
fastify.route({
method: 'GET',
url: '/',
schema: {
// request needs to have a querystring with a `name` parameter
querystring: {
name: { type: 'string' }
},
// 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
beforeHandler: async (request, reply) => {
// E.g. check authentication
},
handler: async (request, reply) => {
return { hello: 'world' }
}
})
const start = async () => {
try {
await fastify.listen(3000)
fastify.log.info(`server listening on ${fastify.server.address().port}`)
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
더 많은 정보는 Documentation에 안내되어있다.
Core features
fastify가 설계된 핵심 기능과 원리는 다음과 같다.
- High performant: fastify는 초당 최대 3만건의 요청을 처리할 수 있는 가장 빠른 웹 프레임워크 중 하나이다.
- Extendible(확장성): fastify는 hooks, plugins, decorators를 활용해 완전히 확장이 가능하다.
- Schema based: 필수는 아니지만 fastify는 JSON schema를 사용하여 경로를 검사하고 출력을 직렬화 하기를 추천한다. fastify는 고성능 function 내의 schema를 컴파일한다.
- Logging: 로그는 매우 중요하지만 비용이 크다. fastify는 이 비용을 없애기 위해 Pino logger를 선택했다.
- Developer friendly: fastify는 개발자들에게 보안 문제의 희생 없이 다양한 표현이 가능하고 일상적으로 사용하는데 도움이 되도록 제작되었다.