Created
August 23, 2023 15:43
-
-
Save tolotrasmile/8b088d088b1faf0f069e584f57cde353 to your computer and use it in GitHub Desktop.
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
import type { RestApi } from './RestApi' | |
/** | |
* Immutable fluent fetch API | |
* | |
* @param baseUrl | |
* @param urls | |
* @param headers | |
* @param params | |
*/ | |
function fluentClient( | |
baseUrl: string, | |
urls: string[] = [], | |
headers: [string, string][] = [], | |
params?: URLSearchParams | |
): RestApi { | |
if (!baseUrl) { | |
throw new Error('baseUrl should not be empty') | |
} | |
return { | |
post(body?: BodyInit | null): Promise<Response> { | |
return fetch(this.getUrl(), { | |
method: 'POST', | |
body, | |
headers, | |
}) | |
}, | |
get(): Promise<Response> { | |
return fetch(this.getUrl(), { | |
method: 'GET', | |
headers, | |
}) | |
}, | |
url(url: string): RestApi { | |
return fluentClient( | |
baseUrl, | |
url ? [...urls, url] : [...url], | |
[...headers], | |
params | |
) | |
}, | |
header(key: string, value: string): RestApi { | |
return fluentClient( | |
baseUrl, | |
[...urls], | |
[...headers, [key, value]], | |
params | |
) | |
}, | |
auth(value: string): RestApi { | |
return fluentClient( | |
baseUrl, | |
[...urls], | |
[...headers, ['Authorization', value]], | |
params | |
) | |
}, | |
setParams(params: URLSearchParams): RestApi { | |
return fluentClient(baseUrl, [...urls], [...headers], params) | |
}, | |
getUrl(): string { | |
return ( | |
[baseUrl, ...urls].join('/') + (params ? `?${params.toString()}` : '') | |
) | |
}, | |
} | |
} | |
export default fluentClient |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment