adguardHomeJoiner/cacheFetch.ts

38 lines
No EOL
819 B
TypeScript

// prevents TS errors
declare const self: Worker;
const transformUrlToFile = (url: string) => {
return url.replace("https://", '').toLowerCase();
}
self.onmessage = async (event: MessageEvent) => {
const fileName = transformUrlToFile(event.data);
const file = Bun.file(`./cache/${fileName}`);
if (await file.exists()) {
const list = await file.text();
self.postMessage(list);
// check if cached file is stale
const req = await fetch(event.data);
const text = await req.text();
if (text !== list) {
return await Bun.write(file, text);
}
} else {
const req = await fetch(event.data);
const text = await req.text();
await Bun.write(file, text);
self.postMessage(text);
}
return;
};