Refactor API calls using a common response handling function
Closed this issue · 1 comments
Description:
Currently, this repository contains several API call functions in the codebase that handle responses individually.
This can lead to code duplication and maintenance challenges as the application grows.
To improve the codebase, I propose refactoring the API calls to use a common response handling function.
Proposed Changes:
I suggest updating the existing API call functions in the codebase to use a single response handling function.
The new function, named handleResponse
, will be responsible for making the API calls and processing the responses.
This refactoring will reduce code duplication and make the codebase more maintainable.
Refactored Code:
api/api.ts
:
const API_URL = 'https://api.spaceflightnewsapi.net/v4';
const handleResponse = async (url) => {
try {
const response = await fetch(url);
if (response.ok) return response.json();
return {
success: false,
error: `Request failed with status code ${response.status}`,
};
} catch (error) {
if (error instanceof Error) {
return {
success: false,
error: error.message,
};
}
}
};
export const getAllArticles = async () => {
return handleResponse(`${API_URL}/articles/?limit=100`);
};
export const getSearchedArticles = async (title) => {
return handleResponse(`${API_URL}/articles/?limit=100&title_contains=${title}`);
};
export const getSearchedNewsSites = async (news_site) => {
return handleResponse(`${API_URL}/articles/?limit=100&news_site=${news_site}`);
};
export const getAllReports = async () => {
return handleResponse(`${API_URL}/reports/?limit=6`);
};
export const getAllInfo = async () => {
return handleResponse(`${API_URL}/info`);
};
Hi @piotr-pajak!
Thank you for your proposal to improve the code in the repository. I agree with you regarding the issue of code duplication and the challenges associated with managing API responses.
I appreciate that you gave me code, but i have additionally added the articles_limit constant for limiting articles and appropriately typed everything. This is a great step towards a more readable and maintainable codebase.
Thank you for your dedication to advancing the project and raising the code quality.
Best regards,
Patryk Penczek