Last active
August 18, 2023 19:43
-
-
Save tolotrasmile/b3713c9fff8d42aa7291f7f11fb56cae 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
export interface RestApi { | |
url(url: string): this | |
post(body?: BodyInit | null): Promise<Response> | |
get(): Promise<Response> | |
auth(value: string): this | |
headers(key: string, value: string): this | |
getUrl(): string | |
params(params: URLSearchParams): this | |
} | |
class RestApiClient implements RestApi { | |
private readonly baseUrl: string | |
private readonly u: string[] = [] | |
private readonly h: [string, string][] = [] | |
private p?: URLSearchParams | |
constructor(baseUrl: string) { | |
this.baseUrl = baseUrl | |
} | |
private request(method: string, body?: BodyInit | null): Promise<Response> { | |
return fetch(this.getUrl(), { | |
body, | |
method, | |
headers: this.h, | |
}) | |
} | |
post(body?: BodyInit | null): Promise<Response> { | |
return this.request('POST', body) | |
} | |
get(): Promise<Response> { | |
return this.request('GET') | |
} | |
url(url: string): this { | |
this.u.push(url) | |
return this | |
} | |
headers(key: string, value: string): this { | |
this.h.push([key, value]) | |
return this | |
} | |
auth(value: string): this { | |
this.h.push(['Authorization', value]) | |
return this | |
} | |
params(params: URLSearchParams): this { | |
this.p = params | |
return this | |
} | |
getUrl(): string { | |
return ( | |
[this.baseUrl, ...this.u].join('/') + | |
(this.p ? `?${this.p.toString()}` : '') | |
) | |
} | |
} | |
export default RestApiClient |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment