본문으로 건너뛰기

copy()

함수 시그니처

copy: () => R

설명

현재 요청 빌더의 설정을 복사하여 같은 종류의 새 빌더를 반환합니다.

GET 또는 DELETE 빌더에서 호출하면 DenchGetBuilder<T>를 반환하고, POST 또는 PUT 빌더에서 호출하면 DenchCreateBuilder<T>를 반환합니다.

copy()RequestInit이나 Header 값을 변경하지 않습니다. 대신 다음 객체를 새로 생성합니다.

  • 빌더의 config 객체
  • config.options 객체
  • config.options.headers 객체가 존재하는 경우 해당 Header 객체
{
...config,
options: {
...config.options,
headers: config.options.headers
? { ...config.options.headers }
: undefined,
body: config.options.body,
},
}

예제

공통 인증과 timeout 설정을 가진 빌더를 여러 요청으로 분기할 수 있습니다.

import { dench } from 'dench-fetch';

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

type Post = {
id: number;
title: string;
};

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

const usersRequest = common.copy().api<User[]>('/users');
const postsRequest = common.copy().api<Post[]>('/posts');

const [users, posts] = await Promise.all([
usersRequest.toJson(),
postsRequest.toJson(),
]);

각 요청에 사용되는 공통 RequestInit과 Header는 다음과 같습니다.

{
method: 'GET',
headers: {
Authorization: 'Bearer access-token',
},
signal: AbortSignal.timeout(3000),
}

복사된 빌더의 주요 객체 관계는 다음과 같습니다.

const copied = common.copy();

copied.config !== common.config;
copied.config.options !== common.config.options;
copied.config.options.headers !== common.config.options.headers;

주의사항

  • copy()는 완전한 깊은 복사가 아닙니다.
  • body가 FormData, Blob 등 참조 객체라면 원본 빌더와 복사된 빌더가 같은 body 객체를 공유합니다.
  • AbortController, AbortSignal, 오류 콜백도 새로운 인스턴스로 복제되지 않습니다.
  • 중단된 AbortController를 가진 빌더를 복사하면 복사된 빌더도 이미 중단된 signal을 사용합니다. 재사용 전에 새로운 컨트롤러를 설정하세요.
  • 복사된 빌더의 Header 객체는 독립적이므로 한 빌더에서 인증 Header를 변경해도 다른 빌더의 Header 객체를 직접 변경하지 않습니다.