Summary
The code generally works but lacks error handling and type safety. The use of 'any' for project type is not ideal, and string concatenation can be improved.
Code Quality Score
75/100
Summary
The code generally works but lacks error handling and type safety. The use of 'any' for project type is not ideal, and string concatenation can be improved.
Issues Found
Line 2
The fetch call does not handle network errors which might lead to unhandled promise rejections or unexpected behavior if the user does not exist or the request fails.
Line 6
The code uses 'any' for the project type which defeats the purpose of TypeScript's type safety features.
Line 2
Using string concatenation for the URL can lead to errors if userId contains unexpected characters or if the base URL changes.
Line 4
The comparison `user.isAdmin == true` can be simplified, as `user.isAdmin` will evaluate to true if it is a truthy value.
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 = await response.json();
if (user.isAdmin) {
console.log('admin user');
}
return {
name: user.name,
projects: user.projects.map((project: Project) => project.title),
};
} catch (error) {
console.error('Failed to fetch user profile:', error);
throw error;
}
}
interface Project {
title: string;
}