Fastify는 최적의 개발자 경험과 압도적인 처리 속도를 제공하는 데 집중한 고효율, 저오버헤드 웹 프레임워크입니다.
시작하기
소개 및 문서
Fastify는 스키마 기반 컴파일과 모듈형 플러그인 아키텍처를 통해 탁월한 처리량을 제공합니다.
- Fastify Source Code (github.com)
- Fastify Documentation (fastify.dev)
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)
경로 선언 (Route Declaration)
fastify.route({
method: 'GET',
url: '/',
schema: { ··· },
handler: (req, reply) => { ··· },
beforeHandler: (req, reply, done) => { ··· }
})
단축 메서드 (Shorthand)
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
})
경로 접두사 (Prefixes)
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')())