HTTP Method Decorators
이 페이지에서 찾을 수 있는 것
| 심볼 | 분류 | 설명 |
|---|---|---|
Get | Decorator | HTTP GET 라우트 등록 |
Post | Decorator | HTTP POST 라우트 등록 |
Put | Decorator | HTTP PUT 라우트 등록 |
Delete | Decorator | HTTP DELETE 라우트 등록 |
IOptions | Interface (미 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| 파라미터 | 타입 | 설명 |
|---|---|---|
path | string | 컨트롤러의 basePath에 대한 상대 URL 경로 세그먼트. Express 경로 파라미터를 지원합니다 (예: '/:id'). basePath 자체와 매칭하려면 '/'를 사용합니다. |
options | IOptions | 라우트 설정 옵션. Swagger 문서 생성, 인증, body/query 형태, 라우트별 미들웨어를 제어합니다. |
IOptions 인터페이스
IOptions는 @asapjs/router의 index.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[];
}필드 레퍼런스
| 필드 | 타입 | 기본값 | 설명 |
|---|---|---|---|
title | string | '' | Swagger UI에 표시되는 오퍼레이션 요약 레이블. |
description | string | '' | Swagger 오퍼레이션 상세 화면에 렌더링되는 긴 설명. |
summary | string | — | Swagger summary 필드의 별칭. |
deprecated | boolean | false | true이면 Swagger UI에서 해당 오퍼레이션을 deprecated로 표시합니다. |
auth | boolean | false | true이면 jwtVerification 미들웨어가 유효한 Bearer 토큰을 요구합니다. jwtVerification을 참고하세요. |
body | DtoOrTypeIs | — | 요청 바디를 설명하는 DTO 클래스 또는 TypeIs.* 표현식. Swagger requestBody 스키마 생성에 사용됩니다. |
bodyContentType | 'application/json' | 'multipart/form-data' | 'application/json' | 요청 바디의 Content-Type. 파일 업로드 시 'multipart/form-data'로 설정합니다. |
query | DtoOrTypeIs | — | 쿼리 스트링 파라미터를 설명하는 DTO 클래스. Swagger 쿼리 파라미터 항목 생성에 사용됩니다. |
response | DtoOrTypeIs | — | HTTP 200 응답 형태를 설명하는 DTO 클래스 또는 TypeIs.* 표현식. |
errors | ErrorCreator[] | — | 이 라우트에서 발생할 수 있는 에러 목록. @asapjs/error의 error() 팩토리로 생성합니다. Swagger에 에러 응답 스키마를 자동 등록합니다. |
middleware | any[] | [] | 이 라우트에만 적용되는 추가 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 };
};
}관련 항목
- RouterController — 컨트롤러 기반 클래스와 라우트 등록
- ExecuteArgs — 핸들러 인수 인터페이스
- jwtVerification —
auth옵션과 JWT 미들웨어 - Swagger — 데코레이터 옵션에서 OpenAPI 스펙 자동 생성
- requestType / responseType — 배열/중첩 DTO 타입 헬퍼
Last updated on