Skip to content

Commit

Permalink
Fixed the number of Github API requests that were being executed twice.
Browse files Browse the repository at this point in the history
  • Loading branch information
ryo-ma committed Sep 28, 2023
1 parent 85f8064 commit a4d50a1
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 15 deletions.
2 changes: 1 addition & 1 deletion index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,4 @@ async function app (req: Request): Promise<Response>{
headers: defaultHeaders,
},
);
};
}
51 changes: 37 additions & 14 deletions src/github_api_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export class GithubAPIClient {
this.requestUserRepository(username),
]);
if (results.some((r) => r == null)) {
console.error(`Can not find a user with username:'${username}'`);
return null;
}
return new UserInfo(results[0]!, results[1]!, results[2]!, results[3]!);
Expand Down Expand Up @@ -109,28 +110,50 @@ export class GithubAPIClient {
private async request(
query: string,
username: string,
retryDelay = CONSTANTS.DEFAULT_GITHUB_RETRY_DELAY,
) {
const tokens = [
Deno.env.get("GITHUB_TOKEN1"),
Deno.env.get("GITHUB_TOKEN2"),
];
const maxRetries = tokens.length;

const variables = { username: username };
let response;
for (const token of tokens) {
response = await soxa.post(
this.apiEndpoint,
{},
{
data: { query: query, variables },
headers: { Authorization: `bearer ${token}` },
},
).catch((error) => {
console.error(error.response.data);
});
if (response.data.data !== undefined) {
break;

for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
response = await soxa.post(
this.apiEndpoint,
{},
{
data: { query: query, variables },
headers: { Authorization: `bearer ${tokens[attempt]}` },
},
);
if (response.data.errors !== undefined) {
throw new Error(
response.data.errors.map((e: { message: string; type: string }) =>
e.message
).join("\n"),
);
}
if (response.data.data !== undefined) {
return response.data.data.user;
} else {
return null;
}
} catch (error) {
console.error(
`Attempt ${attempt} failed with GITHUB_TOKEN${attempt + 1}:`,
error,
);
}

console.log(`Retrying in ${retryDelay / 1000} seconds...`);
await new Promise((resolve) => setTimeout(resolve, retryDelay));
}
return response.data.data.user;

throw new Error(`Max retries (${maxRetries}) exceeded.`);
}
}
1 change: 1 addition & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export const CONSTANTS = {
DEFAULT_NO_BACKGROUND: false,
DEFAULT_NO_FRAME: false,
DEFAULT_GITHUB_API: "https://api.github.com/graphql",
DEFAULT_GITHUB_RETRY_DELAY: 1000,
REVALIDATE_TIME: HOUR_IN_MILLISECONDS,
};

Expand Down

0 comments on commit a4d50a1

Please sign in to comment.