1일 1 TIL를 지키지 않은 점에 대해 반성하며... 오늘은 fastify 간단한 사용법에 대해 알아보려고 한다. 지극히 개인적인 의견이 들어가 있으므로 100% 정확한 내용이 아니라는 점 참고하면서 봐주세요.
내가 fastify를 조금이나마 사용해본 결과, 다음과 같은 이점이 있었던거 같다
공식사이트에서 설명하는(홍보하는) 내용은 다음과 같다.
음..fastify cli가 있긴한데 생각보다 사용률이 없는거 같아서 그냥 직접 설치해서 만들어보기로 함. ... 필자는 타입스크립트를 사용하지 않고 세팅하였다. 예시를 보면서 내게 맞는 방식을 찾아서 세팅함.
예시 : https://github.com/delvedor/fastify-example
예시2 : https://github.com/fastify/fastify-cli/tree/master/templates/app
예시3 : https://github.com/fastify/fastify-autoload
yarn add fastify fastify-autoload
// package.json
{
"name": "server",
"version": "0.0.1",
"main": "index.js",
"license": "MIT",
"type": "module",
"scripts": {
"start": "fastify start -l info app.js",
"dev": "fastify start -w -l info -P app.js"
},
"dependencies": {
"fastify": "^3.23.1",
"fastify-autoload": "^3.9.0"
}
}
scripts를 보면 fastify 관련 명령 옵션이 있는듯하다. (fasity-cli 보면 참고)
// app.js
import AutoLoad from 'fastify-autoload'
import path from 'path'
const __dirname = path.resolve() // 이거 근데 나는 __dirname 자동으로 쓸 수 있을지 알았는데... 아닌가
export default async function (fastify, opts) {
fastify.register(AutoLoad, {
dir: path.join(__dirname, 'routes'),
options: Object.assign({}, opts),
})
}
// ./routes/example/index.js
export default async function example(fastify, opts) {
fastify.get('/', async function (request, reply) {
return 'this is an example'
})
}
fastify-autoload를 사용하니까 폴더 경로가 example인 경우 localhost:3000/example로 접속하면 자동으로 매칭이 되는 것을 알 수 있었다. (이건 좀 편한듯하다)
fastify 기능 중 주요한 기능 가운데 하나로 플러그인이라는게 있다.
다음은 fastify example에서 설명하는 그림이다.
쉽게 말해 plugins란 routes와는 별개로 인터셉터, cors, 인증 등 공통 로직을 처리하기 위한 모듈이라고 보면 될듯하다. 사실 위에 routes 세팅하면서 fastify.register 쓴것도 플러그인인거임...
import fp from 'fastify-plugin'
async function authCallback(fastify, opts) {
fastify.addHook('preHandler', async (request, reply) => {
console.log('pre handler from request')
})
}
export default fp(authCallback, {
name: 'authPlugin',
})
이런식으로 addHook에 preHandler랑 같이 사용하면 인증로직 처리할때 편하다. hook 관련해서 종류는 많으니 공식문서 참고바람. 라이프사이클도 보면 좋을 듯하다