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

HTTP Method Decorators

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

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

개요

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

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

시그니처

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 경로 세그먼트. Express 경로 파라미터를 지원합니다 (예: '/:id'). basePath 자체와 매칭하려면 '/'를 사용합니다.
optionsIOptions라우트 설정 옵션. Swagger 문서 생성, 인증, body/query 형태, 라우트별 미들웨어를 제어합니다.

IOptions 인터페이스

IOptions@asapjs/routerindex.ts에서 re-export되지 않습니다. 사용자가 import { IOptions } 형태로 직접 임포트할 수 없으며, 데코레이터 파라미터의 타입 추론을 통해서만 사용합니다.

interface IOptions { title?: string; description?: string; deprecated?: boolean; summary?: string; auth?: boolean; body?: DtoOrTypeIs; bodyContentType?: 'application/json' | 'multipart/form-data'; query?: DtoOrTypeIs; response?: DtoOrTypeIs; errors?: ErrorCreator[]; middleware?: any[]; }

필드 레퍼런스

필드타입기본값설명
titlestring''Swagger UI에 표시되는 오퍼레이션 요약 레이블.
descriptionstring''Swagger 오퍼레이션 상세 화면에 렌더링되는 긴 설명.
summarystringSwagger summary 필드의 별칭.
deprecatedbooleanfalsetrue이면 Swagger UI에서 해당 오퍼레이션을 deprecated로 표시합니다.
authbooleanfalsetrue이면 jwtVerification 미들웨어가 유효한 Bearer 토큰을 요구합니다. jwtVerification을 참고하세요.
bodyDtoOrTypeIs요청 바디를 설명하는 DTO 클래스 또는 TypeIs.* 표현식. Swagger requestBody 스키마 생성에 사용됩니다.
bodyContentType'application/json' | 'multipart/form-data''application/json'요청 바디의 Content-Type. 파일 업로드 시 'multipart/form-data'로 설정합니다.
queryDtoOrTypeIs쿼리 스트링 파라미터를 설명하는 DTO 클래스. Swagger 쿼리 파라미터 항목 생성에 사용됩니다.
responseDtoOrTypeIsHTTP 200 응답 형태를 설명하는 DTO 클래스 또는 TypeIs.* 표현식.
errorsErrorCreator[]이 라우트에서 발생할 수 있는 에러 목록. @asapjs/errorerror() 팩토리로 생성합니다. Swagger에 에러 응답 스키마를 자동 등록합니다.
middlewareany[][]이 라우트에만 적용되는 추가 Express 미들웨어 함수 배열. JWT 검증 이후, 핸들러 이전에 실행됩니다.

내부 동작

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

// 내부 구현 (참고용) function Route(path: string, method: MethodType, options: IOptions) { return function (target: InstanceType<typeof RouterController>, propertyKey: string) { if (!(target as any).routes) { (target as any).routes = []; } (target as any).routes.push({ method, path, ...options, methodName: propertyKey, }); }; }

미들웨어 실행 순서: jwtVerification(auth)middleware[] 항목들 → Wrapper(handler)

사용 예제

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

관련 항목

Last updated on