1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { feedCache } from "https://esm.town/v/iakovos/feedCache";
import { fetch } from "https://esm.town/v/std/fetch";
import { set } from "https://esm.town/v/std/set?v=11";
export const fetchTextWithCaching = async (url: string): Promise<string | null> => {
const cacheItem = feedCache[url];
const headers: Record<string, string> = {};
if (cacheItem?.etag) {
headers["If-None-Match"] = cacheItem.etag;
}
if (cacheItem?.lastModified) {
headers["If-Modified-Since"] = cacheItem.lastModified;
}
try {
const response = await fetch(url, { headers });
if (response.status === 304) {
console.log("Resource not modified.");
return null;
}
if (response.ok) {
const newContent = await response.text();
feedCache[url] = {
lastFetched: Date.now(),
etag: response.headers.get("ETag") ?? cacheItem?.etag,
lastModified: response.headers.get("Last-Modified")
?? cacheItem?.lastModified,
};
const updatedFeedCache = {
...feedCache,
[url]: {
lastFetched: Date.now(),
etag: response.headers.get("ETag") ?? cacheItem?.etag,
lastModified: response.headers.get("Last-Modified")
?? cacheItem?.lastModified,
},
};
await set("feedCache", updatedFeedCache);
return newContent;
}
else {
throw new Error(`HTTP error! Status: ${response.status}`);
}
}
catch (error) {
console.error("Failed to fetch feeds:", error);
return null;
}
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 24, 2023