Skip to content

Instantly share code, notes, and snippets.

@mxdvl
Last active August 24, 2022 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxdvl/af32e79ed4710f6b53fb50a906b5a75b to your computer and use it in GitHub Desktop.
Save mxdvl/af32e79ed4710f6b53fb50a906b5a75b to your computer and use it in GitHub Desktop.
Get a typed JSON from any API
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);
};
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