Skip to content

Commit

Permalink
fix: Refetch username after delay when github api rate limit is trigg…
Browse files Browse the repository at this point in the history
…ered (#891)

Fixes #859
  • Loading branch information
EGAMAGZ authored Jan 17, 2025
1 parent 8299130 commit 67ba749
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 11 deletions.
13 changes: 12 additions & 1 deletion frontend/islands/GithubUserLink.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,28 @@ import { cachedGitHubLogin } from "../utils/github.ts";

export function GitHubUserLink({ user }: { user?: User }) {
const login = useSignal("");
const error = useSignal(false);

useEffect(() => {
if (user) {
cachedGitHubLogin(user)
.then((login_) => {
login.value = login_;
})
.catch(console.error);
.catch((error_) => {
console.error(error_);

error.value = true;
});
}
});

if (error.value) {
return (
<span class="italic text-[0.625rem]">Could not load GitHub username</span>
);
}

return login.value == ""
? <span>loading...</span>
: <a class="link" href={"https://github.com/" + login.value}>GitHub</a>;
Expand Down
46 changes: 36 additions & 10 deletions frontend/utils/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,41 @@ import { getOrInsertItem } from "./client_cache.ts";
export async function cachedGitHubLogin(user: User): Promise<string> {
return await getOrInsertItem(
`gh-login-${user.githubId}`,
() =>
fetch(`https://api.github.com/user/${user.githubId}`, {
headers: {
"Content-Type": "application/json",
},
})
.then((r) => r.json())
.then((data) => {
return data.login;
}),
() => {
const MAX_RETRIES = 3;
const fetchGithubUser = async (retryCount = 0) => {
const response = await fetch(
`https://api.github.com/user/${user.githubId}`,
{
headers: {
"Content-Type": "application/json",
},
},
);

if (
response.status === 403 &&
response.headers.get("x-ratelimit-remaining") === "0"
) {
throw new Error("Github API rate limit exceeded");
}

const data = await response.json();

if (!data.login) {
if (retryCount >= MAX_RETRIES) {
throw new Error(
"Failed to fetch GitHub login after maximum retries",
);
}

await new Promise((resolve) => setTimeout(resolve, 100));
return fetchGithubUser(retryCount + 1);
}
return data.login;
};

return fetchGithubUser();
},
);
}

0 comments on commit 67ba749

Please sign in to comment.