Skip to content

Commit b6ba6d3

Browse files
committed
refactor: Code refactor for Problem API
1 parent 67767de commit b6ba6d3

File tree

1 file changed

+23
-18
lines changed

1 file changed

+23
-18
lines changed

frontend/src/api/problemApi.ts

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,32 @@
11
// apis for fetching problems for code arena
22

3-
import { PROBLEM_ROUTE } from "@/constants";
43

5-
// api to get all the problems
6-
export const getAllProblems = async () => {
7-
const response = await fetch(`${PROBLEM_ROUTE}/all`);
8-
9-
if (!response.ok) {
10-
throw new Error("Failed to fetch problems");
4+
const fetchWithErrorHandling = async (url: string, options = {}) => {
5+
try {
6+
const response = await fetch(url, options);
7+
if (!response.ok) {
8+
const errorDetails = await response.json().catch(() => ({}));
9+
throw new Error(
10+
errorDetails.message ||
11+
`Error ${response.status}: ${response.statusText}`
12+
);
13+
}
14+
return await response.json();
15+
} catch (error) {
16+
// @ts-expect-error : 'type of error message'
17+
console.error(`API Error: ${error.message}`);
18+
throw error;
1119
}
20+
};
1221

13-
const data = await response.json();
14-
return data;
22+
// api to get all problems
23+
export const getAllProblems = async () => {
24+
const url = `${import.meta.env.VITE_PROBLEM_API_URL}/all`;
25+
return await fetchWithErrorHandling(url);
1526
};
1627

17-
// api to get the single problem by id
28+
// api to get problem by id
1829
export const getProblemById = async (id: string) => {
19-
const response = await fetch(`${PROBLEM_ROUTE}/get/${id}`);
20-
21-
if (!response.ok) {
22-
throw new Error("Failed to fetch problem");
23-
}
24-
25-
const result = await response.json();
26-
return result;
30+
const url = `${import.meta.env.VITE_PROBLEM_API_URL}/get/${id}`;
31+
return await fetchWithErrorHandling(url);
2732
};

0 commit comments

Comments
 (0)