HttpUtil
HttpUtil
リトライ・タイムアウト対応の HTTP クライアント
概要
HttpUtil は fetch をラップした HTTP クライアント。自動リトライ、タイムアウト、Result 型によるエラーハンドリングを提供する。
関数
| 関数 | シグネチャ | 説明 |
|---|---|---|
get | <T>(url, config?) => Promise<Result<T, HttpError>> | GET リクエスト |
post | <T>(url, body?, config?) => Promise<Result<T, HttpError>> | POST リクエスト |
put | <T>(url, body?, config?) => Promise<Result<T, HttpError>> | PUT リクエスト |
patch | <T>(url, body?, config?) => Promise<Result<T, HttpError>> | PATCH リクエスト |
del | <T>(url, config?) => Promise<Result<T, HttpError>> | DELETE リクエスト |
fetchWithRetry | <T>(url, method, body?, config?) => Promise<Result<T, HttpError>> | リトライ付きリクエスト |
型
HttpError
type HttpError = {
status: number | undefined;
message: string;
url: string;
method: string;
};RequestConfig
type RequestConfig = {
headers?: HeadersInit;
retry?: Partial<RetryConfig>;
timeout?: number;
signal?: AbortSignal;
};RetryConfig
type RetryConfig = {
maxRetries: number; // デフォルト: 3
baseDelay: number; // デフォルト: 500ms
retryOnMethods: string[]; // デフォルト: ["GET", "HEAD", "OPTIONS"]
retryOnStatus: (status: number) => boolean; // デフォルト: status >= 500
};デフォルト設定
| 設定 | 値 |
|---|---|
maxRetries | 3 |
baseDelay | 500ms |
retryOnMethods | GET, HEAD, OPTIONS |
retryOnStatus | ステータス >= 500 |
timeout | 30,000ms |
使用例
import { HttpUtil } from "@unitto/utility";
// GET
const result = await HttpUtil.get<User[]>("/api/users");
if (result.ok) {
console.log(result.data);
} else {
console.error(result.error.message);
}
// POST
const created = await HttpUtil.post<User>("/api/users", {
name: "Taro",
email: "taro@example.com",
});
// カスタム設定
const custom = await HttpUtil.get<Data>("/api/data", {
timeout: 5000,
retry: { maxRetries: 5 },
headers: { Authorization: "Bearer xxx" },
});