Created
June 18, 2024 17:11
-
-
Save jfstn/2361bb0b695c6d424e9f5ce87ca049d7 to your computer and use it in GitHub Desktop.
Typesafe Fetch using Zod
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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