|
1 | 1 | // apis for fetching problems for code arena |
2 | 2 |
|
3 | | -import { PROBLEM_ROUTE } from "@/constants"; |
4 | 3 |
|
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; |
11 | 19 | } |
| 20 | +}; |
12 | 21 |
|
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); |
15 | 26 | }; |
16 | 27 |
|
17 | | -// api to get the single problem by id |
| 28 | +// api to get problem by id |
18 | 29 | 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); |
27 | 32 | }; |
0 commit comments