Summary
The code has a good structure and performs well but has some areas for improvement regarding error handling and type safety.
Code Quality Score
75/100
Summary
The code has a good structure and performs well but has some areas for improvement regarding error handling and type safety.
Issues Found
Line 2-3
The code doesn't handle potential errors from the fetch operation or JSON parsing. If the request fails or returns an invalid JSON, it will throw an unhandled promise rejection.
Line 4-5
The type of the response from the API is not defined. Using 'any' for projects can lead to runtime errors as you expect specific properties.
Line 6
The comparison 'user.isAdmin == true' is unnecessary. It can be simplified to 'user.isAdmin'.
Improved Code
export async function getUserProfile(userId: string) {
try {
const response = await fetch("/api/users/" + userId);
if (!response.ok) {
throw new Error("Network response was not ok");
}
const user: User = await response.json();
if (user.isAdmin) {
console.log("admin user");
}
return {
name: user.name,
projects: user.projects.map((project) => project.title),
};
} catch (error) {
console.error("Failed to fetch user profile:", error);
throw error;
}
}
interface User {
name: string;
isAdmin: boolean;
projects: { title: string }[];
}