Skip to content

Commit

Permalink
Add enhancedFetch utility for improved API requests
Browse files Browse the repository at this point in the history
  • Loading branch information
ReihaneB committed Feb 25, 2024
1 parent 3926cda commit 4632998
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/utils/enhancedFetch/enhancedFetch.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
export interface FetchParams {
method: string;
path?: string;
tag: string;
headers?: Record<string, string>;
payload?: Record<string, unknown>;
state?: 'static' | 'dynamic';
responseType?: 'json' | 'text' | 'blob';
timeout?: number;
}

export interface FetchResponse {
status: number;
ok: boolean;
body: Record<string, unknown> | string | Blob;
}

export interface RequestInit {
method?: string;
headers?: Record<string, string>;
body?: string;
withCredentials?: boolean;
next?: {
tags: string[];
};
cache?: 'default' | 'no-store' | 'force-cache';
}
68 changes: 68 additions & 0 deletions src/utils/enhancedFetch/enhancedFetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import type { FetchParams, FetchResponse, RequestInit } from './enhancedFetch.d';

async function enhancedFetch({
method,
path = '',
tag,
headers = {},
payload,
state = 'static',
responseType = 'json',
}: FetchParams): Promise<FetchResponse> {
const options: RequestInit = {
method,
withCredentials: true,
headers: {
'Content-Type': 'application/json',
...headers,
},
next: {
tags: [tag],
},
cache: state === 'dynamic' ? 'no-store' : 'force-cache',
body: payload ? JSON.stringify(payload) : undefined,
};

try {
const result = await fetch(`${process.env.API_URL}${path}`, options);

let body;
switch (responseType) {
case 'json':
body = await result.json();
break;
case 'text':
body = await result.text();
break;
case 'blob':
body = await result.blob();
break;
default:
body = await result.json();
}

return {
status: result.status,
ok: result.ok,
body,
};
} catch (error: unknown) {
let errorMessage: string;
if (error instanceof Error) {
errorMessage = `An error occurred while fetching data: ${error.message}`;
return {
status: error.name === 'AbortError' ? 408 : 500,
ok: false,
body: { message: errorMessage },
};
}
errorMessage = 'An unknown error occurred';
return {
status: 500,
ok: false,
body: { message: errorMessage },
};
}
}

export default enhancedFetch;

0 comments on commit 4632998

Please sign in to comment.