FastifyRouterPlugin
이 페이지에서 찾을 수 있는 것
| 심볼 | 분류 | 설명 |
|---|---|---|
FastifyRouterPlugin | Class | Fastify 라우팅, 미들웨어, 에러 핸들러를 초기화하는 ASAPJS 플러그인 |
개요
FastifyRouterPlugin은 AsapJSPlugin 인터페이스를 구현하는 플러그인 클래스입니다. FastifyApplication의 extensions 배열에 '@asapjs/fastify'를 포함하면 자동으로 등록됩니다. CORS 설정, 전역 미들웨어 적용, 컨트롤러 마운트, 에러 핸들러 등록, 헬스체크 엔드포인트 등록을 자동으로 수행합니다.
import { FastifyRouterPlugin } from '@asapjs/fastify';클래스 정의
class FastifyRouterPlugin implements AsapJSPlugin {
name: string; // '@asapjs/fastify'
async init(config: AsapJSConfig, context: PluginContext): Promise<void>;
}| 멤버 | 타입 | 설명 |
|---|---|---|
name | string | 플러그인 식별자. '@asapjs/fastify'로 고정. |
init(config, context) | async (AsapJSConfig, PluginContext) => void | 플러그인 초기화 메서드. FastifyApplication이 부트스트랩 시 호출합니다. |
init() 동작 순서
init() 메서드가 호출되면 다음 순서로 초기화를 수행합니다:
1. CORS 등록
@fastify/cors 플러그인을 Fastify에 등록합니다. 모든 출처에서의 요청을 허용합니다.
2. 전역 미들웨어 적용
config.router.middleware 배열에 설정된 미들웨어를 Fastify에 등록합니다. Express 스타일 미들웨어는 adaptMiddlewareToHook으로 Fastify preHandler 훅으로 변환됩니다.
3. 라우트 로드 및 등록
config.dirname의 route.ts 파일에서 컨트롤러 배열을 로드합니다. 각 컨트롤러의 basePath를 prefix로 사용하여 Fastify 플러그인 시스템에 등록하고, registerFastifyRoutes(fastify)를 호출하여 라우트를 바인딩합니다.
4. 에러 핸들러 등록
app.setErrorHandler(fastifyErrorHandler)를 호출하여 전역 에러 핸들러를 등록합니다.
5. 헬스체크 엔드포인트 등록
GET /health-check 엔드포인트를 자동으로 등록합니다. 서버가 정상 동작 중임을 확인하는 데 사용합니다.
자동 등록 엔드포인트
| 엔드포인트 | 조건 | 설명 |
|---|---|---|
GET /health-check | 항상 | 서버 동작 확인 |
FastifyApplication에서 활성화하는 방법
FastifyRouterPlugin은 직접 인스턴스화하지 않습니다. FastifyApplication 생성 시 extensions 배열에 '@asapjs/fastify'를 포함하면 자동으로 활성화됩니다:
import { FastifyApplication } from '@asapjs/fastify';
new FastifyApplication(__dirname, {
name: 'My API',
port: 3000,
basePath: 'api',
extensions: ['@asapjs/fastify'],
}).run();route.ts 파일 구조
FastifyRouterPlugin은 config.dirname/route.ts에서 컨트롤러 배열을 로드합니다. 파일은 FastifyRouterController 인스턴스 배열을 기본 내보내기로 제공해야 합니다:
// src/route.ts
import UserController from './user/controller/UserController';
import PostController from './post/controller/PostController';
import CommentController from './comment/controller/CommentController';
export default [
new UserController(),
new PostController(),
new CommentController(),
];각 컨트롤러 인스턴스에서 basePath를 읽어 Fastify 플러그인 prefix로 사용합니다. 인스턴스가 아닌 클래스나 expressRouter만 내보내면 basePath를 읽을 수 없으므로 반드시 인스턴스 자체를 내보내세요.
RouterPlugin과의 비교
@asapjs/router의 RouterPlugin과 비교했을 때 다음 차이가 있습니다:
| 항목 | RouterPlugin | FastifyRouterPlugin |
|---|---|---|
| 대상 프레임워크 | Express | Fastify |
| CORS | cors() 미들웨어 | @fastify/cors 플러그인 |
| 바디 파서 | bodyParser.json() 수동 등록 | Fastify 내장 |
| Swagger UI | 자동 생성 및 등록 | 미지원 |
| 에러 핸들러 | errorHandler (Express) | fastifyErrorHandler (Fastify) |
| 컨트롤러 타입 | RouterController | FastifyRouterController |
| 플러그인 식별자 | '@asapjs/router' | '@asapjs/fastify' |
전체 예제
// src/index.ts
import { FastifyApplication } from '@asapjs/fastify';
require('dotenv').config({ path: `${__dirname}/../.env` });
const port = parseInt(process.env.PORT || '3000', 10);
new FastifyApplication(__dirname, {
name: 'My Fastify API',
port,
basePath: 'api',
extensions: ['@asapjs/fastify', '@asapjs/sequelize'],
database: {
database: process.env.DB_NAME || 'mydb',
username: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD || '',
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT || '3306', 10),
dialect: 'mysql',
logging: false,
},
}).run();// src/route.ts
import UserController from './user/controller/UserController';
import PostController from './post/controller/PostController';
export default [
new UserController(),
new PostController(),
];관련 항목
- FastifyApplication — 플러그인을 활성화하는 애플리케이션 클래스
- FastifyRouterController — 플러그인이 마운트하는 컨트롤러 클래스
- fastifyErrorHandler — 플러그인이 등록하는 에러 핸들러
- RouterPlugin — Express 기반 라우터 플러그인 비교