Skip to content

Instantly share code, notes, and snippets.

@tolotrasmile
Last active August 18, 2023 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tolotrasmile/b3713c9fff8d42aa7291f7f11fb56cae to your computer and use it in GitHub Desktop.
Save tolotrasmile/b3713c9fff8d42aa7291f7f11fb56cae to your computer and use it in GitHub Desktop.
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