Last active
November 2, 2021 20:32
-
-
Save fridezlucas/901d339421c7dc06ed1affa7e8d505f1 to your computer and use it in GitHub Desktop.
Medium TypeScript GET+ POST RESTful client - ApiClient
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
import Axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"; | |
type HttpVerb = "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; | |
class ApiClient { | |
private static singleton: ApiClient; | |
private readonly instanceAxios: AxiosInstance; | |
private URL: string = "https://localhost:44300/"; | |
private constructor() { | |
this.instanceAxios = Axios.create({ | |
baseURL: `${this.URL}api/`, | |
headers: { | |
"Content-Type": "application/json", | |
Accept: "application/json", | |
}, | |
}); | |
} | |
public static get instance(): ApiClient { | |
if (!ApiClient.singleton) { | |
this.singleton = new ApiClient(); | |
} | |
return ApiClient.singleton; | |
} | |
private async request<T>(method: HttpVerb, url: string, body?: any): Promise<T> { | |
const requestConfig: AxiosRequestConfig = { | |
method: method === "GET" ? "GET" : "POST", | |
url: url, | |
headers: {/*... */}, | |
}; | |
// Use X-HTTP-Method-Override to use all HTTP verbs | |
// Verbs will be encapsulated in POST Header | |
if (method !== "GET" && method !== "POST") | |
requestConfig.headers["X-HTTP-Method-Override"] = method; | |
if (body) { | |
requestConfig.data = body; | |
} | |
try { | |
const response: AxiosResponse = await this.instanceAxios(requestConfig); | |
return response.data as T; | |
} catch (error) { | |
throw new Error(error.response.data); | |
} | |
} | |
public async get<T>(url: string): Promise<T> { | |
try { | |
const response: AxiosResponse = await this.instanceAxios.get(url); | |
return response.data as T; | |
} catch (error) { | |
throw new Error(/*..*/); | |
} | |
} | |
public async post<T>(url: string, body: any): Promise<T> { | |
return this.request("POST", url, body); | |
} | |
public async put<T>(url: string, body: any): Promise<T> { | |
return this.request("PUT", url, body); | |
} | |
public async patch<T>(url: string, body?: any, ): Promise<T> { | |
return this.request("PATCH", url, body); | |
} | |
public delete<T>(url: string): Promise<T> { | |
return this.request("DELETE", url); | |
} | |
} | |
export default ApiClient.instance; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment