UNPKG

autumn-js

Version:
70 lines (67 loc) 1.9 kB
"use client"; import { AutumnClientError } from "./chunk-IC3QHWR6.mjs"; // src/react/client/internal/httpClient.ts var isErrorBody = (body) => { return !!body && typeof body === "object" && "message" in body && "code" in body && "statusCode" in body; }; var createHttpClient = (config) => { const { backendUrl, pathPrefix, includeCredentials, headers: customHeaders } = config; const baseUrl = backendUrl ? `${backendUrl}${pathPrefix}` : pathPrefix; const request = async ({ route, body, method = "POST" }) => { const url = `${baseUrl}/${route}`; const headers = { "Content-Type": "application/json", ...customHeaders }; try { const response = await fetch(url, { method, headers, ...includeCredentials && { credentials: "include" }, ...body !== void 0 && { body: JSON.stringify(body) } }); const statusCode = response.status; if (statusCode === 204) { return null; } const result = await response.json(); if (!response.ok) { const error = isErrorBody(result) ? new AutumnClientError(result) : new AutumnClientError({ message: result?.message || "Request failed", code: result?.code || "request_failed", statusCode }); console.error(`[Autumn] ${error.message}`); throw error; } return result; } catch (error) { if (error instanceof AutumnClientError) { throw error; } const message = error instanceof Error ? error.message : "Network error"; const autumnError = new AutumnClientError({ message, code: "network_error", statusCode: 0 }); console.error(`[Autumn] ${autumnError.code}: ${autumnError.message}`); throw autumnError; } }; return { request }; }; export { createHttpClient };