diff --git a/example.env b/example.env index c8b280f..49387fe 100644 --- a/example.env +++ b/example.env @@ -1 +1,2 @@ TBA_AUTH_KEY="your key here" +CACHE_PATH=.cache diff --git a/index.ts b/index.ts index 3bf49a2..ed41fb0 100644 --- a/index.ts +++ b/index.ts @@ -1,8 +1,8 @@ import "dotenv/config"; -const AUTH_KEY = Bun.env.TBA_AUTH_KEY; +const AUTH_KEY = Bun.env.TBA_AUTH_KEY as string; if (!AUTH_KEY) { - process.exit(); + process.exit(1); } const authHeaders = new Headers({ @@ -17,7 +17,28 @@ interface CacheEntry { staleTime: number; } -const tbaCache: { [name: string]: CacheEntry } = {}; +const CACHE_PATH = Bun.env.CACHE_PATH as string; +if (!CACHE_PATH) { + process.exit(1); +} + +async function initializeCache() { + let data = {}; + + const cacheFile = Bun.file(".cache"); + if (cacheFile.size > 0) { + data = JSON.parse(await cacheFile.text()); + } + + console.log(Object.keys(data)); + return data; +} + +const tbaCache: { [name: string]: CacheEntry } = await initializeCache(); + +async function writeCache() { + Bun.write(CACHE_PATH, JSON.stringify(tbaCache)); +} interface TBAResponse { data: string; @@ -31,7 +52,7 @@ function updateCache( maxAge: number, ) { if (etag) { - tbaCache[endpoint] = { etag, data, staleTime: Date.now() + maxAge }; + tbaCache[endpoint] = { etag, data, staleTime: Date.now() + maxAge * 1000 }; } } @@ -41,7 +62,6 @@ function fetchCache(endpoint: string) { async function getTBAEndpoint(endpoint: string): Promise { const time = Date.now(); - console.log(tbaCache[endpoint]); if (tbaCache[endpoint] && tbaCache[endpoint].staleTime > time) { console.log("Cache hit... " + endpoint); return { data: fetchCache(endpoint).data, status: 200 }; @@ -80,5 +100,5 @@ async function getTBAEndpoint(endpoint: string): Promise { const response = await getTBAEndpoint("/team/frc4043/events/simple"); -console.log(response); +writeCache();