Cache github token

This commit is contained in:
johnd0e
2024-03-03 01:41:44 +01:00
parent 645b9551c4
commit 5059cffa15
2 changed files with 24 additions and 8 deletions

View File

@@ -1,5 +1,5 @@
export default {
async fetch (request) {
async fetch (request, env) {
if (request.method === "OPTIONS") {
return handleOPTIONS(request);
}
@@ -14,8 +14,26 @@ export default {
status: 401
});
}
const { token, errResponse } = await getToken(authKey);
const tokenCache = env.KV;
let token;
try {
token = await tokenCache.get(authKey);
} catch (e) {
console.error(e);
}
if (!token) {
let errResponse;
({ token, errResponse } = await getToken(authKey));
if (errResponse) { return errResponse; }
const expiration = token.match(/;exp=(\d+);/)?.[1];
if (expiration) {
try {
await tokenCache.put(authKey, token, { expiration });
} catch (e) {
console.error(e);
}
}
}
return makeRequest(request, url.pathname, await makeHeaders(token));
}
};

View File

@@ -3,8 +3,6 @@ main = "src/worker.mjs"
compatibility_date = "2024-01-17"
no_bundle = true
# Bind a KV Namespace. Use KV as persistent storage for small key-value pairs.
# Docs: https://developers.cloudflare.com/workers/runtime-apis/kv
# [[kv_namespaces]]
# binding = "MY_KV_NAMESPACE"
# id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
[[kv_namespaces]]
binding = "KV"
id = "4e595a4637f048ed8c92bab1821c6e54"