Skip to Content
API 레퍼런스@asapjs/fastifyHTTP Method Decorators

HTTP Method Decorators

이 페이지에서 찾을 수 있는 것

심볼분류설명
GetDecoratorHTTP GET 라우트 등록
PostDecoratorHTTP POST 라우트 등록
PutDecoratorHTTP PUT 라우트 등록
DeleteDecoratorHTTP DELETE 라우트 등록
IOptionsInterface데코레이터 옵션 설정

개요

@asapjs/fastify는 네 가지 HTTP 메서드 데코레이터를 제공합니다. 모든 데코레이터는 동일한 시그니처를 가지며, FastifyRouterController를 상속한 클래스의 메서드에 적용합니다.

import { Get, Post, Put, Delete } from '@asapjs/fastify';

시그니처

function Get(path: string, options?: IOptions): MethodDecorator function Post(path: string, options?: IOptions): MethodDecorator function Put(path: string, options?: IOptions): MethodDecorator function Delete(path: string, options?: IOptions): MethodDecorator
파라미터타입설명
pathstring컨트롤러의 basePath에 대한 상대 URL 경로 세그먼트. Fastify 경로 파라미터를 지원합니다 (예: '/:id'). basePath 자체와 매칭하려면 '/'를 사용합니다.
optionsIOptions라우트 설정 옵션. body/query 형태, 라우트별 미들웨어, 에러 목록을 제어합니다. 기본값은 {}.

IOptions 인터페이스

IOptions@asapjs/fastifyindex.ts에서 타입으로 re-export됩니다.

import type { IOptions } from '@asapjs/fastify';
interface IOptions { title?: string; description?: string; deprecated?: boolean; body?: any; bodyContentType?: 'application/json' | 'multipart/form-data'; query?: any; response?: any; errors?: ErrorCreator[]; middleware?: any[]; }

필드 레퍼런스

필드타입기본값설명
titlestring''라우트를 설명하는 레이블. 문서화 목적으로 사용합니다.
descriptionstring''라우트에 대한 상세 설명.
deprecatedbooleanfalsetrue이면 해당 라우트가 더 이상 사용되지 않음을 표시합니다.
bodyany요청 바디를 설명하는 DTO 클래스 또는 스키마.
bodyContentType'application/json' | 'multipart/form-data''application/json'요청 바디의 Content-Type.
queryany쿼리 스트링 파라미터를 설명하는 DTO 클래스.
responseanyHTTP 200 응답 형태를 설명하는 DTO 클래스.
errorsErrorCreator[]이 라우트에서 발생할 수 있는 에러 목록. @asapjs/errorerror() 팩토리로 생성합니다.
middlewareany[][]이 라우트에만 적용되는 추가 미들웨어 함수 배열. Express 스타일 미들웨어를 전달하면 adaptMiddlewareToHook이 Fastify preHandler로 자동 변환합니다.

@asapjs/router 데코레이터와의 차이점

@asapjs/router의 HTTP 메서드 데코레이터와 비교했을 때 다음 차이가 있습니다:

항목@asapjs/router@asapjs/fastify
auth 옵션있음 (JWT 검증)없음
summary 옵션있음 (Swagger alias)없음
Swagger 자동 생성지원미지원
미들웨어 변환Express 미들웨어 직접 사용adaptMiddlewareToHook으로 변환

errors 옵션과 error() 팩토리

errors 옵션에는 @asapjs/errorerror() 팩토리로 생성한 에러 생성자를 전달합니다. 라우트 핸들러에서 해당 에러를 던지면 fastifyErrorHandler가 적절한 HTTP 상태 코드와 에러 바디로 응답합니다.

import { error } from '@asapjs/error'; const UserNotFound = error(404, 'USER_NOT_FOUND', '사용자를 찾을 수 없습니다'); const InvalidInput = error(400, 'INVALID_INPUT', '잘못된 입력값입니다');

내부 동작

데코레이터가 메서드에 적용되면, 내부 Route() 함수가 라우트 디스크립터 객체(method, path, options, methodName)를 클래스 프로토타입의 routes 배열에 추가합니다. 이 배열은 이후 FastifyRouterPluginregisterFastifyRoutes(fastify)를 호출할 때 순회하면서 Fastify에 등록합니다.

미들웨어 실행 순서: middleware[] 항목들(preHandler로 변환) → FastifyWrapper(handler)


사용 예제

import { FastifyRouterController, Get, Post, Put, Delete, FastifyExecuteArgs } from '@asapjs/fastify'; import { error } from '@asapjs/error'; import UserApplication from '../application/UserApplication'; import CreateUserDto from '../dto/CreateUserDto'; import UserInfoDto from '../dto/UserInfoDto'; // 에러 정의 const UserNotFound = error(404, 'USER_NOT_FOUND', '사용자를 찾을 수 없습니다'); export default class UserController extends FastifyRouterController { public basePath = '/users'; public tag = 'User'; private userService: UserApplication; constructor() { super(); this.userService = new UserApplication(); } @Get('/', { title: '사용자 목록 조회', description: '페이지네이션을 지원하는 사용자 목록을 조회합니다.', }) public getUserList = async ({ paging }: FastifyExecuteArgs) => { return await this.userService.list(paging); }; @Get('/:userId', { title: '사용자 상세 조회', errors: [UserNotFound], }) public getUserById = async ({ path }: FastifyExecuteArgs<{ userId: string }>) => { return await this.userService.info(path?.userId); }; @Post('/', { title: '사용자 생성', body: CreateUserDto, response: UserInfoDto, }) public createUser = async ({ body }: FastifyExecuteArgs<{}, {}, CreateUserDto>) => { return await this.userService.create(body); }; @Put('/:userId', { title: '사용자 수정', body: CreateUserDto, response: UserInfoDto, }) public updateUser = async ({ path, body }: FastifyExecuteArgs<{ userId: string }, {}, CreateUserDto>) => { return await this.userService.update(path?.userId, body); }; @Delete('/:userId', { title: '사용자 삭제', errors: [UserNotFound], }) public deleteUser = async ({ path }: FastifyExecuteArgs<{ userId: string }>) => { await this.userService.delete(path?.userId); return { success: true }; }; }

관련 항목

Last updated on