feat: respect cache headers

This commit is contained in:
Travis Fischer
2020-07-21 08:31:51 -04:00
parent 35e48d1d3f
commit 0177ebafa9
3 changed files with 29 additions and 8 deletions

16
src/get-cache-key.ts Normal file
View File

@@ -0,0 +1,16 @@
export function getCacheKey(request: Request): string | null {
const pragma = request.headers.get("pragma");
if (pragma === "no-cache") {
return null;
}
const cacheControl = request.headers.get("cache-control");
if (cacheControl) {
const directives = new Set(cacheControl.split(",").map((s) => s.trim()));
if (directives.has("no-store") || directives.has("no-cache")) {
return null;
}
}
return request.url;
}

View File

@@ -6,6 +6,7 @@ import { tableRoute } from "./routes/table";
import { userRoute } from "./routes/user";
import { searchRoute } from "./routes/search";
import { createResponse } from "./response";
import { getCacheKey } from "./get-cache-key";
import * as types from "./api/types";
export type Handler = (
@@ -55,14 +56,14 @@ const handleRequest = async (fetchEvent: FetchEvent): Promise<Response> => {
return new Response("Endpoint not found.", { status: 404 });
}
const cacheKey = request.url;
const cacheKey = getCacheKey(request);
let response;
try {
const cachedResponse = await cache.match(cacheKey);
if (cachedResponse) {
response = cachedResponse;
}
} catch (err) {}
if (cacheKey) {
try {
response = await cache.match(cacheKey);
} catch (err) {}
}
const getResponseAndPersist = async () => {
const res = await match.handler({
@@ -72,7 +73,10 @@ const handleRequest = async (fetchEvent: FetchEvent): Promise<Response> => {
notionToken,
});
await cache.put(cacheKey, res.clone());
if (cacheKey) {
await cache.put(cacheKey, res.clone());
}
return res;
};

View File

@@ -10,6 +10,7 @@ export const createResponse = (
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Content-Type": "application/json",
...headers,
},
});