Skip to content

Commit

Permalink
Refactor: 'getLikes' async function in 'involvementAPI.ts'
Browse files Browse the repository at this point in the history
- Removed unnecessary try-catch block in the `getLikes` function.
Instead, if the response is not ok, the function now throws an error
class with the response `statusText` as the message.
This refactor improves the clarity and efficiency of error handling.
  • Loading branch information
ITurres committed Mar 9, 2024
1 parent df361b4 commit 1db80c9
Showing 1 changed file with 14 additions and 16 deletions.
30 changes: 14 additions & 16 deletions src/services/involvementAPI/involvementAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,23 @@ const postLike = async (itemId: string) => {
};

const getLikes = async () => {
try {
const response = await fetch(`${baseURL}${appId}/likes/`, {
method: 'GET',
});

if (!response.ok) return [];
const response = await fetch(`${baseURL}${appId}/likes/`, {
method: 'GET',
});

// * Only parse the response if it's JSON.
// * specially when the involvementAPI : 'appId' is new, the response to be parsed wont be JSON.
const contentType = response.headers.get('Content-Type');
if (contentType && contentType.includes('application/json')) {
const likes = await response.json();
if (likes instanceof Array) return likes;
}
if (!response.ok) {
throw new Error(`Error fetching likes: ${response.statusText}`);
}

return [];
} catch (error) {
return error;
// * Only parse the response if it's JSON.
// * specially when the involvementAPI : 'appId' is new, the response to be parsed wont be JSON.
const contentType = response.headers.get('Content-Type');
if (contentType && contentType.includes('application/json')) {
const likes = await response.json();
if (likes instanceof Array) return likes;
}

return [];
};

const involvement = {
Expand Down

0 comments on commit 1db80c9

Please sign in to comment.