Created
June 12, 2025 12:54
-
-
Save sangdth/15e3d0b21d721017f0342b94ee2a218e to your computer and use it in GitHub Desktop.
fetcher.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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