FastifyApplication
이 페이지에서 찾을 수 있는 것
| 심볼 | 분류 | 설명 |
|---|---|---|
FastifyApplication | Class | Fastify HTTP 서버 부트스트랩 및 플러그인 관리 |
constructor | Method | 애플리케이션 인스턴스 생성 |
run() | Method | 플러그인 초기화 후 서버 시작 |
getApp() | Method | 내부 FastifyInstance 반환 |
getServer() | Method | 내부 http.Server 반환 |
destroy() | Method | 서버 종료 및 리소스 정리 |
개요
FastifyApplication은 @asapjs/fastify의 진입점 클래스입니다. __dirname과 설정 객체로 인스턴스를 생성한 후 run()을 호출하면, extensions 배열에 선언된 플러그인을 순서대로 초기화하고 Fastify HTTP 서버를 시작합니다.
import { FastifyApplication } from '@asapjs/fastify';클래스 정의
class FastifyApplication {
constructor(dirname: string, config: AsapJSConfig);
public run(
initBeforeStartServer?: (app: FastifyInstance) => void | Promise<void>
): Promise<FastifyInstance>;
public getApp(): FastifyInstance;
public getServer(): http.Server;
public async destroy(): Promise<void>;
}생성자
new FastifyApplication(dirname: string, config: AsapJSConfig)| 파라미터 | 타입 | 설명 |
|---|---|---|
dirname | string | 컴파일된 출력 디렉터리의 절대 경로. 엔트리 파일에서 __dirname을 전달합니다. FastifyRouterPlugin이 route.ts를 탐색하는 기준 경로로 사용됩니다. |
config | AsapJSConfig | 애플리케이션 설정 객체. 전역으로 저장되며 getConfig()를 통해 조회할 수 있습니다. |
run()
application.run(
initBeforeStartServer?: (app: FastifyInstance) => void | Promise<void>
): Promise<FastifyInstance>플러그인을 순서대로 초기화한 후 HTTP 서버를 시작합니다. Fastify 인스턴스를 반환합니다.
| 파라미터 | 타입 | 설명 |
|---|---|---|
initBeforeStartServer | (app: FastifyInstance) => void | Promise<void> | 플러그인 초기화 완료 후, server.listen() 이전에 호출되는 선택적 콜백. 초기화된 FastifyInstance를 인수로 받습니다. |
run() 내부 초기화 순서:
FastifyRouterPlugin.init()—extensions에'@asapjs/fastify'가 있는 경우: CORS를 등록하고, 전역 미들웨어를 적용하며,dirname/route.ts에서 컨트롤러를 로드하고, 에러 핸들러와 헬스체크 엔드포인트를 등록합니다.SequelizePlugin.init()—extensions에'@asapjs/sequelize'가 있는 경우: 데이터베이스에 연결하고 모델을 등록합니다.initBeforeStartServer(app)콜백 — 사용자 정의 시작 로직.app.listen({ port: config.port, host: '0.0.0.0' })— HTTP 서버를 시작합니다.
getApp()
application.getApp(): FastifyInstance내부 FastifyInstance를 동기적으로 반환합니다. run() 호출 전에는 undefined입니다.
getServer()
application.getServer(): http.ServerFastify가 내부적으로 생성한 http.Server 인스턴스를 반환합니다. run() 호출 전에는 undefined입니다.
destroy()
await application.destroy(): Promise<void>등록된 플러그인을 정리하고 Fastify 서버를 종료합니다. 테스트 환경에서 서버를 정상적으로 종료하거나 graceful shutdown을 구현할 때 사용합니다.
process.on('SIGTERM', async () => {
await app.destroy();
process.exit(0);
});전체 예제
// src/index.ts
import { FastifyApplication } from '@asapjs/fastify';
require('dotenv').config({ path: `${__dirname}/../.env` });
const port = parseInt(process.env.PORT || '3000', 10);
const app = 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,
},
});
app.run(async (fastify) => {
// 서버 시작 직전에 실행할 로직
// fastify 인스턴스에 직접 접근 가능
console.log('서버 시작 준비 완료');
});중요:
extensions배열에'@asapjs/fastify'를 반드시 포함해야 합니다. 누락하면 라우팅, 전역 미들웨어, 헬스체크 엔드포인트가 활성화되지 않습니다.
관련 항목
- FastifyRouterPlugin — 플러그인 초기화 동작 상세
- FastifyRouterController — 컨트롤러 기반 클래스
- FastifyExecuteArgs — 라우트 핸들러 인수 타입
- @asapjs/core — Express 기반 Application 클래스
Last updated on