Skip to content

Commit

Permalink
Refactor fetchApi
Browse files Browse the repository at this point in the history
  • Loading branch information
ruchernchong committed Dec 18, 2024
1 parent 478a575 commit de33c53
Showing 1 changed file with 12 additions and 19 deletions.
31 changes: 12 additions & 19 deletions utils/fetchApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,14 @@ export const fetchApi = async <T>(
url: string,
options: RequestInit = {},
): Promise<T> => {
const defaultOptions: RequestInit = {
headers: {
Authorization: `Bearer ${process.env.SG_CARS_TRENDS_API_TOKEN}`,
},
};

const mergedOptions: RequestInit = {
...defaultOptions,
...options,
headers: {
...defaultOptions.headers,
...options.headers,
},
};

try {
const response = await fetch(url, mergedOptions);
const response = await fetch(url, {
...options,
headers: {
Authorization: `Bearer ${process.env.SG_CARS_TRENDS_API_TOKEN}`,
...options.headers,
},
});

if (!response.ok) {
throw new Error(
Expand All @@ -27,8 +18,10 @@ export const fetchApi = async <T>(
}

return response.json();
} catch (e: any) {
console.error(e.message);
throw e;
} catch (error) {
console.error(
`Fetch error: ${error instanceof Error ? error.message : error}`,
);
throw error;
}
};

0 comments on commit de33c53

Please sign in to comment.