I asked chatgpt for a fetch json utility function using the result pattern, thoughts?
interface FetchJsonOptions extends RequestInit {
// you could add extra app-specific options here if needed
}
interface FetchSuccess<T> {
success: true;
data: T;
headers: Headers;
}
interface FetchFailure {
success: false;
error: string;
}
type FetchResult<T> = FetchSuccess<T> | FetchFailure;
export async function fetchJson<T>(
url: string,
options: FetchJsonOptions = {}
): Promise<FetchResult<T>> {
try {
const response = await fetch(url, {
headers: {
"Content-Type": "application/json",
...(options.headers ?? {}),
},
...options,
});
if (!response.ok) {
return {
success: false,
error: `HTTP ${response.status}: ${response.statusText}`,
};
}
const data: T = await response.json();
return {
success: true,
data,
headers: response.headers,
};
} catch (err: unknown) {
return {
success: false,
error: (err as Error).message,
};
}
}