Skip to content

Commit

Permalink
fix: update user search to fallback to GitHub API on error and zero r…
Browse files Browse the repository at this point in the history
…esults
  • Loading branch information
brandonroberts committed Jun 17, 2024
1 parent 603a444 commit 50ddc50
Showing 1 changed file with 50 additions and 27 deletions.
77 changes: 50 additions & 27 deletions lib/hooks/search-users.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,55 @@
async function searchOpenSaucedAPI(username: string) {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/users/search?username=${encodeURIComponent(
username.replaceAll("user:", "")
)}&limit=5`
);

return response;
}

async function searchGitHubAPI(username: string, providerToken?: string | null | undefined) {
const response = await fetch(
`https://api.github.com/search/users?q=${encodeURIComponent(username)} type:user&sort=followers&per_page=5`,
{
...(providerToken
? {
headers: {
Authorization: `Bearer ${providerToken}`,
},
}
: {}),
}
);

return response;
}

const searchUsers = async (username: string, providerToken?: string | null | undefined) => {
try {
const fallbackResponse = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/users/search?username=${encodeURIComponent(
username.replaceAll("user:", "")
)}&limit=5`
);
if (fallbackResponse.status === 200) {
const data = ((await fallbackResponse.json()).data as DbUser[]).map((user) => ({
id: user.id,
login: user.login,
full_name: user.name,
updated_at: user.updated_at,
})) as unknown as GhUser[];
return { data };
} else if (fallbackResponse.status === 403) {
// Use our API as a fallback
const res = await fetch(
`https://api.github.com/search/users?q=${encodeURIComponent(username)} type:user&sort=followers&per_page=5`,
{
...(providerToken
? {
headers: {
Authorization: `Bearer ${providerToken}`,
},
}
: {}),
}
);
const response = await searchOpenSaucedAPI(username);

if (response.status === 200) {
const responseData = ((await response.json()).data as DbUser[]) || [];

if (responseData.length > 0) {
const data = responseData.map((user) => ({
id: user.id,
login: user.login,
full_name: user.name,
updated_at: user.updated_at,
})) as unknown as GhUser[];

return { data };
}

const res = await searchGitHubAPI(username, providerToken);
const githubUserData = (await res.json()).items as GhUser[];

return { data: githubUserData };
} else if (response.status === 403) {
const res = await searchGitHubAPI(username, providerToken);

if (res.status === 200) {
const data = (await res.json()).items as GhUser[];
return { data };
Expand Down

0 comments on commit 50ddc50

Please sign in to comment.