-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
17 additions
and
1 deletion.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,26 @@ | ||
import QuickLRU from "quick-lru"; | ||
import { z } from "zod"; | ||
|
||
const cache = new QuickLRU({ | ||
// 100 items. | ||
maxSize: 100, | ||
|
||
// 5 minutes. | ||
maxAge: 5 * 60 * 1000, | ||
}); | ||
|
||
export const fetchData = async <T extends z.ZodTypeAny>( | ||
schema: T, | ||
url: string, | ||
headers?: Record<string, string>, | ||
): Promise<z.TypeOf<T>> => { | ||
const cacheKey = JSON.stringify({ url, headers }); | ||
const cachedJson = cache.get(cacheKey); | ||
if (cachedJson) { | ||
return schema.parse(cachedJson) as z.infer<T>; | ||
} | ||
const response = await fetch(url, { headers }); | ||
const json = await response.json(); | ||
const json = (await response.json()) as unknown; | ||
cache.set(cacheKey, json); | ||
return schema.parse(json) as z.infer<T>; | ||
}; |