Last active
August 24, 2022 16:40
-
-
Save mxdvl/af32e79ed4710f6b53fb50a906b5a75b to your computer and use it in GitHub Desktop.
Get a typed JSON from any API
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
export const fetchJSON = async <T>( | |
url: Parameters<typeof fetch>[0], | |
{ | |
headers, | |
parser, | |
}: { | |
headers?: Record<string, string>; | |
parser: (data: unknown) => T | Promise<T>; | |
} | |
): Promise<T> => { | |
const data: unknown = await fetch(url, { headers }).then((r) => r.json()); | |
return parser(data); | |
}; |
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 { object, number } from "https://deno.land/x/zod@v3.17.3/mod.ts"; | |
import { fetchJSON } from "./json.ts"; | |
const sourcesSchema = object({ | |
base_experience: number(), | |
}); | |
const { base_experience } = await fetchJSON( | |
"https://pokeapi.co/api/v2/pokemon/ditto", | |
{ | |
parser: sourcesSchema.parseAsync, | |
} | |
); | |
console.log(base_experience); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment