FastifyExecuteArgs
이 페이지에서 찾을 수 있는 것
| 심볼 | 분류 | 설명 |
|---|---|---|
FastifyExecuteArgs<P,Q,B,Context> | Generic Type | 라우트 핸들러의 단일 인수 타입 |
FastifyWrapper | Function | 핸들러를 Fastify 라우트 핸들러로 변환 |
개요
@asapjs/fastify의 모든 라우트 핸들러는 단일 FastifyExecuteArgs 인수를 받습니다. 내부의 FastifyWrapper가 Fastify의 FastifyRequest/FastifyReply 객체에서 관련 필드를 추출하여, 정규화되고 타입이 지정된 형태로 핸들러에 전달합니다.
import { FastifyExecuteArgs, FastifyWrapper } from '@asapjs/fastify';FastifyExecuteArgs 타입 정의
export type FastifyExecuteArgs<P = {}, Q = {}, B = {}, Context = {}> = {
req: FastifyRequest;
res: FastifyReply;
path: P & Record<string, any>;
query: Q & Record<string, any>;
body: B & Record<string, any>;
paging: { page: number; limit: number };
} & Context;제네릭 파라미터
네 가지 제네릭 타입 파라미터는 모두 선택 사항입니다.
| 파라미터 | 대상 필드 | 설명 |
|---|---|---|
P | path | URL 경로 파라미터 타입 (예: { userId: string }) |
Q | query | 쿼리 스트링 파라미터 타입 |
B | body | 요청 바디 타입 (예: DTO 클래스) |
Context | 교차 타입 | 추가 컨텍스트 필드 타입. 미들웨어가 주입하는 커스텀 데이터를 타입으로 표현할 때 사용합니다. |
필드 레퍼런스
| 필드 | 타입 | 출처 | 설명 |
|---|---|---|---|
req | FastifyRequest | Fastify 요청 객체 | 원시 Fastify FastifyRequest. 다른 필드에서 다루지 않는 항목(헤더, 쿠키, IP 등)에 사용합니다. |
res | FastifyReply | Fastify 응답 객체 | 원시 Fastify FastifyReply. 커스텀 응답(예: 파일 스트림)을 직접 전송해야 할 때만 사용합니다. |
path | P & Record<string, any> | request.params | Fastify가 파싱한 URL 경로 파라미터. 키는 라우트 경로의 :name 세그먼트와 일치합니다. |
query | Q & Record<string, any> | request.query | 파싱된 쿼리 스트링 객체. page와 limit 키는 별도로 소비되어 paging으로 들어갑니다. |
body | B & Record<string, any> | request.body | 파싱된 요청 바디. application/json 요청의 경우 JSON 디코딩된 객체입니다. |
paging | { page: number; limit: number } | request.query.page, request.query.limit | 미리 파싱된 페이지네이션 객체. 항상 존재하며, 기본값은 page: 0, limit: 20. |
Express ExecuteArgs와의 차이점
@asapjs/router의 ExecuteArgs와 비교했을 때 다음 차이가 있습니다:
| 항목 | ExecuteArgs | FastifyExecuteArgs |
|---|---|---|
req 타입 | Express.Request | FastifyRequest |
res 타입 | Express.Response | FastifyReply |
files 필드 | 있음 (req.files) | 없음 |
user 필드 | 있음 (req.user, JWT 페이로드) | 없음 (기본 제공 없음) |
| 추가 컨텍스트 | 없음 | Context 제네릭으로 확장 가능 |
| 알 수 없는 프로퍼티 | 직접 접근 불가 | Proxy로 request에서 포워딩 |
FastifyExecuteArgs는 req 객체에 Proxy를 적용하여, 정의되지 않은 프로퍼티에 접근하면 자동으로 FastifyRequest에서 해당 값을 찾아 반환합니다.
FastifyWrapper
export function FastifyWrapper(
cb: (args: FastifyExecuteArgs) => Promise<unknown>,
): (request: FastifyRequest, reply: FastifyReply) => Promise<void>FastifyWrapper는 FastifyExecuteArgs를 받는 핸들러 함수를 Fastify가 직접 호출할 수 있는 라우트 핸들러로 변환합니다. 모든 데코레이터 라우트에 자동으로 적용되므로 직접 사용할 일은 거의 없습니다.
FastifyWrapper가 FastifyExecuteArgs를 구성하는 방법
request.query.page(기본값0)와request.query.limit(기본값20)를 정수로 파싱하여paging객체를 생성합니다.request.params,request.query,request.body,paging값으로FastifyExecuteArgs객체를 조립합니다.req에 Proxy를 적용하여 알 수 없는 프로퍼티 접근을request로 포워딩합니다.FastifyExecuteArgs를 인수로 핸들러를await합니다.- 핸들러가 truthy 값을 반환하면
reply.status(200).send(output)으로 응답합니다.
에러 처리
FastifyWrapper는 핸들러에서 던져진 에러를 다음 규칙으로 처리합니다:
| 에러 유형 | 조건 | HTTP 상태 | 바디 |
|---|---|---|---|
HttpError (@asapjs/error) | error() 팩토리로 생성 | err.status | { status, errorCode, message, data } |
| status + message 객체 | status와 message 속성 있음 | err.status | HttpError로 래핑 후 동일 형식 |
| 처리되지 않은 오류 | 위 조건 모두 해당 없음 | 500 | { status: 500, errorCode: 'INTERNAL_SERVER_ERROR', message } |
응답 반환 패턴
// 객체 반환 → HTTP 200 JSON
async getUser({ path }: FastifyExecuteArgs<{ userId: string }>) {
return await this.userService.info(path?.userId);
}
// undefined 반환 → 자동 응답 안 됨 (reply 직접 사용)
async downloadFile({ res, path }: FastifyExecuteArgs) {
const stream = await this.fileService.getStream(path?.fileId);
res.header('Content-Disposition', `attachment; filename="${path?.fileId}"`);
return res.send(stream);
}
// { success: true } → 삭제 등 바디 없는 작업의 관례
async deleteUser({ path }: FastifyExecuteArgs<{ userId: string }>) {
await this.userService.delete(path?.userId);
return { success: true };
}Context 제네릭 활용
미들웨어가 요청 객체에 추가 데이터를 주입하는 경우, Context 제네릭으로 타입을 확장할 수 있습니다:
type AuthContext = { userId: number; role: string };
@Get('/profile', {
middleware: [authMiddleware],
})
public getProfile = async ({ userId, role }: FastifyExecuteArgs<{}, {}, {}, AuthContext>) => {
return await this.userService.profile(userId);
};관련 항목
- HTTP Method Decorators —
IOptions와 데코레이터 사용법 - 에러 핸들러 — 전역 Fastify 에러 핸들러
- ExecuteArgs (@asapjs/router) — Express 기반 핸들러 인수 타입 비교
Last updated on