Skip to main content

api()

함수 시그니처

api: <P = T>(api: string) => DenchCreateBuilder<P>

설명

POST 또는 PUT 요청 빌더의 API 경로를 변경합니다. 공통 설정을 구성한 빌더를 여러 API 경로에 재사용할 때 사용할 수 있습니다.

제네릭 P를 지정하면 이후 toJson()의 반환 타입도 함께 변경됩니다.

api()RequestInit이나 Header를 변경하지 않습니다. 변경된 경로는 base URL과 결합되어 fetch()의 첫 번째 인자로 사용됩니다.

예제

import { dench } from 'dench-fetch';

type CreatedUser = {
id: number;
name: string;
};

const common = dench('https://api.example.com')
.post()
.auth('access-token');

const user = await common
.copy()
.api<CreatedUser>('/users')
.sendJson({ name: 'Dench' })
.toJson();

api() 호출 후 요청 설정은 다음과 같습니다.

{
baseURL: 'https://api.example.com',
api: '/users',
options: {
method: 'POST',
headers: {
Authorization: 'Bearer access-token',
},
},
}

sendJson()까지 적용한 실제 요청은 다음과 같습니다.

fetch('https://api.example.com/users', {
method: 'POST',
headers: {
Authorization: 'Bearer access-token',
'Content-Type': 'application/json',
},
body: '{"name":"Dench"}',
});

주의사항

  • api()는 HTTP 메서드와 기존 요청 설정을 유지하고 API 경로만 변경합니다.
  • P는 컴파일 타임 응답 타입이며 런타임 응답을 검증하지 않습니다.
  • 독립적인 요청으로 분기하려면 copy().api() 형태를 사용하세요.