Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: update user search to fallback to GitHub API on error and zero results #3569

Merged
merged 1 commit into from
Jun 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading