Skip to Content

ExecuteArgs

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

심볼분류설명
ExecuteArgs<P,Q,B>Generic Interface라우트 핸들러의 단일 인수 타입

개요

ASAPJS의 모든 라우트 핸들러는 단일 ExecuteArgs 인수를 받습니다. 내부의 Wrapper 유틸리티가 Express의 Request/Response 객체에서 관련 필드를 추출하여, 정규화되고 타입이 지정된 형태로 핸들러에 전달합니다.

import { ExecuteArgs } from '@asapjs/router';

인터페이스 정의

export interface ExecuteArgs<P = {}, Q = {}, B = {}> { req: Request; res: Response; path?: P | { [key: string]: any }; query: Q & { [key: string]: any }; body: B & { [key: string]: any }; files?: { [key: string]: any }; user?: any; paging: PaginationQueryType; }

제네릭 파라미터

세 가지 제네릭 타입 파라미터는 모두 선택 사항이며, path, query, body의 추론 타입을 각각 좁히는 데 사용합니다.

파라미터대상 필드설명
PpathURL 경로 파라미터 타입 (예: { userId: string })
Qquery쿼리 스트링 파라미터 타입
Bbody요청 바디 타입 (예: DTO 클래스)

필드 레퍼런스

필드타입출처설명
reqRequestExpress 요청 객체원시 Express Request. 다른 필드에서 다루지 않는 항목(헤더, 쿠키, IP 등)에 사용합니다.
resResponseExpress 응답 객체원시 Express Response. 커스텀 응답(예: 파일 스트림)을 직접 전송해야 할 때만 사용합니다.
pathP | { [key: string]: any }req.paramsExpress가 파싱한 URL 경로 파라미터. 키는 라우트 경로의 :name 세그먼트와 일치합니다. 모든 값은 문자열입니다.
queryQ & { [key: string]: any }req.query파싱된 쿼리 스트링 객체. pagelimit 키는 별도로 소비되어 paging으로 들어갑니다.
bodyB & { [key: string]: any }req.body파싱된 요청 바디. application/json 요청의 경우 JSON 디코딩된 객체입니다.
files{ [key: string]: any }req.filesmultipart/form-data 요청의 파일 업로드. 파일 업로드 미들웨어(예: multer)가 설정된 경우에만 존재합니다.
useranyreq.user유효한 Bearer 토큰이 있을 때 jwtVerification이 설정하는 디코딩된 JWT 페이로드. 토큰이 없는 라우트에서는 undefined.
pagingPaginationQueryTypereq.query.page, req.query.limit미리 파싱된 페이지네이션 객체 { page, limit }. 항상 존재하며, 기본값은 page: 0, limit: 20.

Wrapper가 ExecuteArgs를 구성하는 방법

Wrapper 함수는 등록된 모든 라우트 핸들러에 적용되며, 다음 순서로 동작합니다:

  1. req.query.page(기본값 0)와 req.query.limit(기본값 20)를 정수로 파싱하여 PaginationQueryType 객체를 생성합니다.
  2. req.user, req.query, req.params, req.body, paging 값으로 ExecuteArgs 객체를 조립합니다.
  3. ExecuteArgs를 인수로 핸들러를 await합니다.
  4. 핸들러가 truthy 값을 반환하면 res.status(200).json(output)으로 응답합니다.
  5. 던져진 오류를 잡아 @asapjs/errorerrorToResponse()로 위임합니다.

응답 반환 패턴

// 객체 반환 → HTTP 200 JSON async getUser({ path }: ExecuteArgs<{ userId: string }>) { return await this.userService.info(path?.userId); } // undefined 반환 → 자동 응답 안 됨 (res 직접 사용) async downloadFile({ res, path }: ExecuteArgs) { const stream = await this.fileService.getStream(path?.fileId); res.setHeader('Content-Disposition', `attachment; filename="${path?.fileId}"`); stream.pipe(res); } // { success: true } → 삭제 등 바디 없는 작업의 관례 async deleteUser({ path }: ExecuteArgs<{ userId: string }>) { await this.userService.delete(path?.userId); return { success: true }; }

오류 처리

경로 1: Wrapper 내부 — errorToResponse()

라우트 핸들러에서 던져진 에러는 Wrapper의 try/catch에서 잡혀 @asapjs/errorerrorToResponse()로 위임됩니다.

에러 유형조건HTTP 상태바디
HttpError (@asapjs/error)error() 팩토리로 생성err.status{ status, errorCode, message, data }
HttpException (legacy)statusmessage만 있고 errorCode 없음err.status{ status, errorCode: 'LEGACY_HTTP_EXCEPTION', message }
처리되지 않은 오류status 속성 없음500{ status: 500, errorCode: 'INTERNAL_SERVER_ERROR', message }

새 코드에서는 @asapjs/errorerror() 팩토리를 사용하세요. 자세한 내용은 @asapjs/error를 참고하세요.

경로 2: Express 전역 에러 핸들러 — errorHandler

Wrapper를 거치지 않는 에러(예: 미들웨어에서 next(error) 호출)는 Express 미들웨어 체인 끝에 등록된 errorHandler(@asapjs/router)가 처리합니다.

에러 유형HTTP 상태바디
HttpExceptionerr.status{ status, message }
일반 에러500{ status: 500, message }
import { HttpException } from '@asapjs/router'; throw new HttpException(404, 'Post not found'); // → HTTP 404 { status: 404, message: 'Post not found' }

PaginationQueryType

ExecuteArgs.paging의 타입은 @asapjs/sequelize에서 제공하는 PaginationQueryType입니다.

type PaginationQueryType = { page: number; limit: number };
필드타입쿼리 파라미터기본값설명
pagenumber?page=00 기반 페이지 인덱스
limitnumber?limit=20페이지당 레코드 수

Swagger 문서화에는 PaginationQueryDto를 데코레이터의 query 옵션에 전달합니다. paging 필드는 query 설정 여부와 관계없이 Wrapper가 항상 채워줍니다.

관련 항목

Last updated on