Skip to Content

FastifyExecuteArgs

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

심볼분류설명
FastifyExecuteArgs<P,Q,B,Context>Generic Type라우트 핸들러의 단일 인수 타입
FastifyWrapperFunction핸들러를 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;

제네릭 파라미터

네 가지 제네릭 타입 파라미터는 모두 선택 사항입니다.

파라미터대상 필드설명
PpathURL 경로 파라미터 타입 (예: { userId: string })
Qquery쿼리 스트링 파라미터 타입
Bbody요청 바디 타입 (예: DTO 클래스)
Context교차 타입추가 컨텍스트 필드 타입. 미들웨어가 주입하는 커스텀 데이터를 타입으로 표현할 때 사용합니다.

필드 레퍼런스

필드타입출처설명
reqFastifyRequestFastify 요청 객체원시 Fastify FastifyRequest. 다른 필드에서 다루지 않는 항목(헤더, 쿠키, IP 등)에 사용합니다.
resFastifyReplyFastify 응답 객체원시 Fastify FastifyReply. 커스텀 응답(예: 파일 스트림)을 직접 전송해야 할 때만 사용합니다.
pathP & Record<string, any>request.paramsFastify가 파싱한 URL 경로 파라미터. 키는 라우트 경로의 :name 세그먼트와 일치합니다.
queryQ & Record<string, any>request.query파싱된 쿼리 스트링 객체. pagelimit 키는 별도로 소비되어 paging으로 들어갑니다.
bodyB & 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/routerExecuteArgs와 비교했을 때 다음 차이가 있습니다:

항목ExecuteArgsFastifyExecuteArgs
req 타입Express.RequestFastifyRequest
res 타입Express.ResponseFastifyReply
files 필드있음 (req.files)없음
user 필드있음 (req.user, JWT 페이로드)없음 (기본 제공 없음)
추가 컨텍스트없음Context 제네릭으로 확장 가능
알 수 없는 프로퍼티직접 접근 불가Proxy로 request에서 포워딩

FastifyExecuteArgsreq 객체에 Proxy를 적용하여, 정의되지 않은 프로퍼티에 접근하면 자동으로 FastifyRequest에서 해당 값을 찾아 반환합니다.


FastifyWrapper

export function FastifyWrapper( cb: (args: FastifyExecuteArgs) => Promise<unknown>, ): (request: FastifyRequest, reply: FastifyReply) => Promise<void>

FastifyWrapperFastifyExecuteArgs를 받는 핸들러 함수를 Fastify가 직접 호출할 수 있는 라우트 핸들러로 변환합니다. 모든 데코레이터 라우트에 자동으로 적용되므로 직접 사용할 일은 거의 없습니다.

FastifyWrapper가 FastifyExecuteArgs를 구성하는 방법

  1. request.query.page(기본값 0)와 request.query.limit(기본값 20)를 정수로 파싱하여 paging 객체를 생성합니다.
  2. request.params, request.query, request.body, paging 값으로 FastifyExecuteArgs 객체를 조립합니다.
  3. req에 Proxy를 적용하여 알 수 없는 프로퍼티 접근을 request로 포워딩합니다.
  4. FastifyExecuteArgs를 인수로 핸들러를 await합니다.
  5. 핸들러가 truthy 값을 반환하면 reply.status(200).send(output)으로 응답합니다.

에러 처리

FastifyWrapper는 핸들러에서 던져진 에러를 다음 규칙으로 처리합니다:

에러 유형조건HTTP 상태바디
HttpError (@asapjs/error)error() 팩토리로 생성err.status{ status, errorCode, message, data }
status + message 객체statusmessage 속성 있음err.statusHttpError로 래핑 후 동일 형식
처리되지 않은 오류위 조건 모두 해당 없음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); };

관련 항목

Last updated on