-
-
Notifications
You must be signed in to change notification settings - Fork 349
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore(fetch): add custom mutator test for
fetch
client
- Loading branch information
1 parent
82940ca
commit 25d64c8
Showing
2 changed files
with
74 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
// NOTE: Supports cases where `content-type` is other than `json` | ||
const getBody = <T>(c: Response | Request): Promise<T> => { | ||
const contentType = c.headers.get('content-type'); | ||
|
||
if (contentType && contentType.includes('application/json')) { | ||
return c.json(); | ||
} | ||
|
||
if (contentType && contentType.includes('application/pdf')) { | ||
return c.blob() as Promise<T>; | ||
} | ||
|
||
return c.text() as Promise<T>; | ||
}; | ||
|
||
// NOTE: Update just base url | ||
const getUrl = (contextUrl: string): string => { | ||
const url = new URL(contextUrl); | ||
const pathname = url.pathname; | ||
const search = url.search; | ||
const baseUrl = | ||
process.env.NODE_ENV === 'production' | ||
? 'productionBaseUrl' | ||
: 'http://localhost:3000'; | ||
|
||
const requestUrl = new URL(`${baseUrl}${pathname}${search}`); | ||
|
||
return requestUrl.toString(); | ||
}; | ||
|
||
// NOTE: Add headers | ||
const getHeaders = (headers?: HeadersInit): HeadersInit => { | ||
return { | ||
...headers, | ||
Authorization: 'token', | ||
'Content-Type': 'multipart/form-data', | ||
}; | ||
}; | ||
|
||
export const customFetch = async <T>( | ||
url: string, | ||
options: RequestInit, | ||
): Promise<T> => { | ||
const requestUrl = getUrl(url); | ||
const requestHeaders = getHeaders(options.headers); | ||
|
||
const requestInit: RequestInit = { | ||
...options, | ||
headers: requestHeaders, | ||
}; | ||
|
||
const request = new Request(requestUrl, requestInit); | ||
const response = await fetch(request); | ||
const data = await getBody<T>(response); | ||
|
||
return data; | ||
}; |