Skip to content

Commit

Permalink
feat: add caching
Browse files Browse the repository at this point in the history
  • Loading branch information
velut committed Apr 17, 2024
1 parent 9bf300c commit e7e749a
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"isomorphic-unfetch": "^4.0.2",
"make-error": "^1.3.6",
"query-string": "^9.0.0",
"quick-lru": "^7.0.0",
"tiny-lru": "^11.2.5",
"url-join": "^5.0.0",
"validate-npm-package-name": "^5.0.0",
Expand Down
17 changes: 16 additions & 1 deletion src/fetch-data.ts
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>;
};

0 comments on commit e7e749a

Please sign in to comment.