Summary
Code is functional but lacks type safety and error handling.
Code Quality Score
75/100
Summary
Code is functional but lacks type safety and error handling.
Issues Found
Line 3-5
The 'user' and 'project' types are not defined, which can lead to potential runtime errors and reduces code clarity.
Line 2
There is no error handling for the fetch request, which can lead to uncaught errors if the network request fails or if the response is not successful.
Line 5
The `user.isAdmin == true` check can be simplified since 'isAdmin' is already a boolean.
Line 8
If the fetch call fails or the user data does not include expected fields, this could lead to runtime errors when accessing properties.
Improved Code
export interface User {
name: string;
isAdmin: boolean;
projects: Project[];
}
export interface Project {
title: string;
}
export async function getUserProfile(userId: string) {
try {
const response = await fetch("/api/users/" + userId);
if (!response.ok) {
throw new Error(`Error fetching user: ${response.statusText}`);
}
const user: User = await response.json();
if (user.isAdmin) {
console.log("admin user");
}
return {
name: user.name,
projects: user.projects ? user.projects.map((project: Project) => project.title) : [],
};
} catch (error) {
console.error(error);
return null; // Or consider throwing an error/rejecting promise
}
}