mirror of
https://github.com/zhigang1992/notion-api-worker.git
synced 2026-01-12 17:32:42 +08:00
feat: respect cache headers
This commit is contained in:
16
src/get-cache-key.ts
Normal file
16
src/get-cache-key.ts
Normal 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;
|
||||
}
|
||||
20
src/index.ts
20
src/index.ts
@@ -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;
|
||||
};
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ export const createResponse = (
|
||||
headers: {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET, OPTIONS",
|
||||
"Content-Type": "application/json",
|
||||
...headers,
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user