Update case transformer

This commit is contained in:
Jamitz 2026-01-15 22:45:38 +00:00
parent eb52756c6d
commit 25af4639bf

View file

@ -3,54 +3,48 @@ import createClient from "openapi-fetch";
import { camelizeKeys, decamelizeKeys } from "humps";
import type { paths } from "@/types/api";
const API_URL = import.meta.env.PROD
? "/api" // ← Same domain, different path
: "http://localhost:8000/api";
const API_URL = import.meta.env.PROD ? "/api" : "http://localhost:8000/api";
// Create the base client with full type safety
export const client = createClient<paths>({
baseUrl: API_URL,
credentials: "include",
});
// Add middleware to automatically transform requests and responses
client.use({
async onRequest({ request }) {
// Transform request body from camelCase to snake_case
if (request.body) {
try {
const bodyText = await request.text();
if (bodyText) {
const bodyJson = JSON.parse(bodyText);
const transformedBody = decamelizeKeys(bodyJson);
const cloned = request.clone();
// Preserve headers and ensure Content-Type is set
const headers = new Headers(request.headers);
if (!headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
try {
const bodyText = await cloned.text();
if (bodyText) {
const bodyJson = JSON.parse(bodyText);
const transformedBody = decamelizeKeys(bodyJson);
return new Request(request.url, {
method: request.method,
headers: headers,
body: JSON.stringify(transformedBody),
credentials: request.credentials,
mode: request.mode,
cache: request.cache,
redirect: request.redirect,
referrer: request.referrer,
integrity: request.integrity,
});
const headers = new Headers(request.headers);
if (!headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
} catch (e) {
// If not JSON, pass through unchanged
return new Request(request.url, {
method: request.method,
headers: headers,
body: JSON.stringify(transformedBody),
credentials: request.credentials,
mode: request.mode,
cache: request.cache,
redirect: request.redirect,
referrer: request.referrer,
integrity: request.integrity,
});
}
} catch (e) {
// If not JSON, pass through unchanged
}
return request;
},
async onResponse({ response }) {
// Transform response body from snake_case to camelCase
if (response.body) {
try {
const clonedResponse = response.clone();
@ -63,7 +57,6 @@ client.use({
headers: response.headers,
});
} catch (e) {
// If not JSON, return original response
return response;
}
}