Skip to content

Instantly share code, notes, and snippets.

@jfstn
Created June 18, 2024 17:11
Show Gist options
  • Save jfstn/2361bb0b695c6d424e9f5ce87ca049d7 to your computer and use it in GitHub Desktop.
Save jfstn/2361bb0b695c6d424e9f5ce87ca049d7 to your computer and use it in GitHub Desktop.
Typesafe Fetch using Zod
import type { z } from 'zod';
import { logger } from '~/server/logger';
export const DEFAULT_HEADERS = {
Accept: 'application/json',
'Content-Type': 'application/json',
};
export async function typesafeFetch<T>(
schema: z.ZodType<T>,
resource: RequestInfo | URL,
init?: RequestInit
) {
try {
const definedInit =
init ||
({
headers: DEFAULT_HEADERS,
method: 'GET',
} satisfies RequestInit);
const response = await fetch(resource, definedInit);
const bodyText = await response.text();
const data = bodyText ? JSON.parse(bodyText) : bodyText;
const parsedData = schema.safeParse(data);
if (!parsedData.success) {
throw 'Failed to parse data';
} else {
return parsedData.data;
}
} catch (error) {
logger.error(`ERROR Failed when fetching ${resource}: ${error}`);
throw error;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment