2026-01-26 11:28:04 -05:00

58 lines
1.5 KiB
TypeScript

import { HoudiniClient, fetch as houdiniFetch } from '$houdini';
const URL = 'https://api.example.com/graphql/';
type RawGraphQLError = { message?: string; [key: string]: unknown };
type RawGraphQLResponse = {
data?: Record<string, unknown> | null;
errors?: RawGraphQLError[] | null;
} | null;
type FetchContext = {
fetch: typeof fetch;
text: string;
variables?: Record<string, unknown>;
};
export default new HoudiniClient({
url: URL,
plugins: [
houdiniFetch(async ({ fetch, text, variables }: FetchContext) => {
const res = await fetch(URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include', // Send cookies with request
body: JSON.stringify({ query: text, variables })
});
let json: RawGraphQLResponse = null;
try {
json = (await res.json()) as RawGraphQLResponse;
} catch (parseError) {
console.warn('Failed to parse JSON response:', parseError);
}
// Normalize response for Houdini
if (json && (json.data !== undefined || json.errors !== undefined)) {
const normalizedErrors =
json.errors?.map((e) => ({
message: typeof e?.message === 'string' ? e.message : 'Unknown error'
})) ?? null;
return {
data: (json.data ?? null) as Record<string, unknown> | null,
errors: normalizedErrors
};
}
const fallbackError =
res && res.status >= 400
? [{ message: `HTTP ${res.status}: ${res.statusText}` }]
: [{ message: 'Network error' }];
return { data: null, errors: fallbackError };
})
]
});