Update case transformer
This commit is contained in:
parent
eb52756c6d
commit
25af4639bf
1 changed files with 25 additions and 32 deletions
|
|
@ -3,28 +3,23 @@ import createClient from "openapi-fetch";
|
||||||
import { camelizeKeys, decamelizeKeys } from "humps";
|
import { camelizeKeys, decamelizeKeys } from "humps";
|
||||||
import type { paths } from "@/types/api";
|
import type { paths } from "@/types/api";
|
||||||
|
|
||||||
const API_URL = import.meta.env.PROD
|
const API_URL = import.meta.env.PROD ? "/api" : "http://localhost:8000/api";
|
||||||
? "/api" // ← Same domain, different path
|
|
||||||
: "http://localhost:8000/api";
|
|
||||||
|
|
||||||
// Create the base client with full type safety
|
|
||||||
export const client = createClient<paths>({
|
export const client = createClient<paths>({
|
||||||
baseUrl: API_URL,
|
baseUrl: API_URL,
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add middleware to automatically transform requests and responses
|
|
||||||
client.use({
|
client.use({
|
||||||
async onRequest({ request }) {
|
async onRequest({ request }) {
|
||||||
// Transform request body from camelCase to snake_case
|
const cloned = request.clone();
|
||||||
if (request.body) {
|
|
||||||
try {
|
try {
|
||||||
const bodyText = await request.text();
|
const bodyText = await cloned.text();
|
||||||
if (bodyText) {
|
if (bodyText) {
|
||||||
const bodyJson = JSON.parse(bodyText);
|
const bodyJson = JSON.parse(bodyText);
|
||||||
const transformedBody = decamelizeKeys(bodyJson);
|
const transformedBody = decamelizeKeys(bodyJson);
|
||||||
|
|
||||||
// Preserve headers and ensure Content-Type is set
|
|
||||||
const headers = new Headers(request.headers);
|
const headers = new Headers(request.headers);
|
||||||
if (!headers.has("Content-Type")) {
|
if (!headers.has("Content-Type")) {
|
||||||
headers.set("Content-Type", "application/json");
|
headers.set("Content-Type", "application/json");
|
||||||
|
|
@ -45,12 +40,11 @@ client.use({
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// If not JSON, pass through unchanged
|
// If not JSON, pass through unchanged
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return request;
|
return request;
|
||||||
},
|
},
|
||||||
|
|
||||||
async onResponse({ response }) {
|
async onResponse({ response }) {
|
||||||
// Transform response body from snake_case to camelCase
|
|
||||||
if (response.body) {
|
if (response.body) {
|
||||||
try {
|
try {
|
||||||
const clonedResponse = response.clone();
|
const clonedResponse = response.clone();
|
||||||
|
|
@ -63,7 +57,6 @@ client.use({
|
||||||
headers: response.headers,
|
headers: response.headers,
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// If not JSON, return original response
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue