Skip to content

Instantly share code, notes, and snippets.

@sangdth
Created June 12, 2025 12:54
Show Gist options
  • Save sangdth/15e3d0b21d721017f0342b94ee2a218e to your computer and use it in GitHub Desktop.
Save sangdth/15e3d0b21d721017f0342b94ee2a218e to your computer and use it in GitHub Desktop.
fetcher.ts
Typescript version:
```typescript
import deepmerge from 'deepmerge';
import { HttpMethod } from '@/types';
export async function fetcher<JSON = unknown>(
input: RequestInfo,
init?: RequestInit
): Promise<JSON> {
const finalOptions = deepmerge(
{
method: HttpMethod.GET,
headers:
init?.body instanceof FormData
? {}
: {
'Content-Type': 'application/json',
},
},
init ?? {}
);
const response = await fetch(input, finalOptions);
// Sometime the body can be empty, and the json() will fail
if (response.status === 204 || response.statusText === 'No Content') {
return JSON.parse('{}');
}
return await response.json();
}
```
Lite version:
```javascript
export async function fetcher<JSON = unknown>(
input: RequestInfo,
init?: RequestInit
): Promise<JSON> {
const defaultOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
};
const response = await fetch(input, {
...defaultOptions,
...init,
});
// Sometime the body can be empty, and the json() will fail
if (response.status === 204 || response.statusText === 'No Content') {
return JSON.parse('{}');
}
return await response.json();
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment