persistent cache

This commit is contained in:
Zynh0722 2024-04-04 00:16:33 -07:00
parent 42cccc77f1
commit dea7825cbc
2 changed files with 27 additions and 6 deletions

View file

@ -1 +1,2 @@
TBA_AUTH_KEY="your key here"
CACHE_PATH=.cache

View file

@ -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<TBAResponse> {
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<TBAResponse> {
const response = await getTBAEndpoint("/team/frc4043/events/simple");
console.log(response);
writeCache();