From a678fe48f2f94847df1a1f6bdfa093f59268b7c3 Mon Sep 17 00:00:00 2001 From: Tri Nguyen Van Date: Thu, 5 Dec 2024 18:15:48 +0100 Subject: [PATCH] fix: api key error on cloudflare --- web/src/server.tsx | 85 ++++++++++++++++++++++++++++------------------ 1 file changed, 52 insertions(+), 33 deletions(-) diff --git a/web/src/server.tsx b/web/src/server.tsx index 3035386d..73420c1b 100644 --- a/web/src/server.tsx +++ b/web/src/server.tsx @@ -1,5 +1,7 @@ "use server"; +import { getRequestEvent } from "solid-js/web"; + const cacheStore: { [pr_number: number]: { result: any; @@ -8,9 +10,14 @@ const cacheStore: { } = {}; export async function fetchRawFile(url: string) { + const event = getRequestEvent(); + const api_key = + event?.nativeEvent.context.cloudflare?.env.GITHUB_ACCESS_TOKEN ?? + process.env.GITHUB_ACCESS_TOKEN; + const response = await fetch(url, { headers: { - Authorization: `Bearer ${process.env.GITHUB_ACCESS_TOKEN}`, + Authorization: `Bearer ${api_key}`, "X-GitHub-Api-Version": "2022-11-28", }, }); @@ -25,41 +32,53 @@ export async function getPRFiles( files: GitFile[]; cacheStatus: string; }> { - const cache = cacheStore[number]; - if (cache) { - const invalidated = new Date(cache.date_iso) < new Date(last_updated_at); - if (invalidated) { - console.log("cache invalidated!", number); - delete cacheStore[number]; + try { + const cache = cacheStore[number]; + if (cache) { + const invalidated = new Date(cache.date_iso) < new Date(last_updated_at); + if (invalidated) { + console.log("cache invalidated!", number); + delete cacheStore[number]; + } else { + console.log("cache hit!", number); + return { + files: cache.result, + cacheStatus: "hit", + }; + } } else { - console.log("cache hit!", number); - return { - files: cache.result, - cacheStatus: "hit", - }; + console.log("cache miss!", number); } - } else { - console.log("cache miss!", number); - } - const response = await fetch( - `https://api.github.com/repos/unibas-tilics/tilics/pulls/${number}/files`, - { - headers: { - Authorization: `Bearer ${process.env.GITHUB_ACCESS_TOKEN}`, - "X-GitHub-Api-Version": "2022-11-28", - }, - } - ); - const json = await response.json(); + const event = getRequestEvent(); + const api_key = + event?.nativeEvent.context.cloudflare?.env.GITHUB_ACCESS_TOKEN ?? + process.env.GITHUB_ACCESS_TOKEN; + const response = await fetch( + `https://api.github.com/repos/unibas-tilics/tilics/pulls/${number}/files`, + { + headers: { + Authorization: `Bearer ${api_key}`, + "X-GitHub-Api-Version": "2022-11-28", + }, + } + ); + const json = await response.json(); - cacheStore[number] = { - result: json, - date_iso: new Date().toISOString(), - }; + cacheStore[number] = { + result: json, + date_iso: new Date().toISOString(), + }; - return { - files: json, - cacheStatus: "miss", - }; + return { + files: json, + cacheStatus: "miss", + }; + } catch (e) { + console.error(e); + return { + files: [], + cacheStatus: "error", + }; + } }