app.use("*", async (c, next) => {
const t = performance.now();
const cache = caches.default;
const cacheUrl = new URL(c.req.url);
const cacheKey = new Request(cacheUrl.toString(), c.req);
let response = await cache.match(cacheKey);
if (response) {
c.env.myData = { cachedData: await response.json() };
console.log("cache hit", performance.now() - t);
return next();
}
const object = await c.env.MY_R2_STORAGE.get("some-data.json");
if (!object) {
throw new Error("Data not found");
}
const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set("etag", object.httpEtag);
const status = object.body ? 200 : 304;
const [body1, body2] = object.body.tee();
response = new Response(body1, {
headers,
status,
});
response.headers.append("Cache-Control", "s-maxage=31536000");
c.executionCtx.waitUntil(cache.put(cacheKey, response));
if (!cachedData) {
throw new Error("Data not found");
}
c.env.myData = { cachedData: await streamToJson(body2) };
console.log("cache miss", performance.now() - t);
return next();
});
app.use("*", async (c, next) => {
const t = performance.now();
const cache = caches.default;
const cacheUrl = new URL(c.req.url);
const cacheKey = new Request(cacheUrl.toString(), c.req);
let response = await cache.match(cacheKey);
if (response) {
c.env.myData = { cachedData: await response.json() };
console.log("cache hit", performance.now() - t);
return next();
}
const object = await c.env.MY_R2_STORAGE.get("some-data.json");
if (!object) {
throw new Error("Data not found");
}
const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set("etag", object.httpEtag);
const status = object.body ? 200 : 304;
const [body1, body2] = object.body.tee();
response = new Response(body1, {
headers,
status,
});
response.headers.append("Cache-Control", "s-maxage=31536000");
c.executionCtx.waitUntil(cache.put(cacheKey, response));
if (!cachedData) {
throw new Error("Data not found");
}
c.env.myData = { cachedData: await streamToJson(body2) };
console.log("cache miss", performance.now() - t);
return next();
});