Last active
August 16, 2024 10:46
-
-
Save NuroDev/4957f92f957d6c26fff216cff4c082fa to your computer and use it in GitHub Desktop.
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
const ChuckNorrisFact = z.object({ | |
icon_url: z.string().url(), | |
id: z.string().min(1), | |
url: z.string(), | |
value: z.string(), | |
}); | |
const UserOptions = z | |
.object({ | |
category: z.enum([ | |
"animal", | |
"career", | |
"celebrity", | |
"dev", | |
"explicit", | |
"fashion", | |
"food", | |
"history", | |
"money", | |
"movie", | |
"music", | |
"political", | |
"religion", | |
"science", | |
"sport", | |
"travel", | |
]), | |
query: z.string().min(1), | |
}) | |
.partial() | |
.optional(); | |
export const chuckNorrisFactsLoader: ( | |
options?: z.infer<typeof UserOptions>, | |
) => Loader = (options) => ({ | |
name: "chuck-norris-facts", | |
load: async (ctx) => { | |
const { category, query } = options || {}; | |
const url = new URL( | |
`/jokes/${query ? "search" : "random"}`, | |
"https://api.chucknorris.io", | |
); | |
if (category) { | |
url.searchParams.append("category", category); | |
} else if (query) { | |
url.searchParams.append("query", query); | |
} | |
const response = await fetch(url.href); | |
const json = (await response.json()) as z.infer<typeof ChuckNorrisFact>; | |
ctx.store.set({ | |
id: json.id, | |
data: json, | |
}); | |
}, | |
schema: ChuckNorrisFact, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment