Created
November 21, 2023 20:18
-
-
Save jsonbytes/09f9af7d376989397f7e79573c7e2b6c to your computer and use it in GitHub Desktop.
API Client written in Typescript
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, { AxiosError, AxiosInstance, AxiosRequestConfig } from "axios"; | |
import { API_BASE_URL } from "../config/apiConfig"; | |
class APIClient<T> { | |
private axiosInstance: AxiosInstance; | |
endpoint: string; | |
constructor(endpoint: string) { | |
this.endpoint = endpoint; | |
this.axiosInstance = axios.create({ baseURL: API_BASE_URL }); | |
} | |
private handleError = (error: AxiosError) => { | |
return Promise.reject(error); | |
}; | |
create = async <U>(data?: T, config?: AxiosRequestConfig) => { | |
console.log(`API client: create`); | |
return this.axiosInstance | |
.post<U>(this.endpoint, data, config) | |
.then((response) => response.data) | |
.catch(this.handleError); | |
}; | |
getAll = async (config?: AxiosRequestConfig) => { | |
console.log(`API client: getAll`); | |
return this.axiosInstance | |
.get<T[]>(this.endpoint, config) | |
.then((response) => response.data) | |
.catch(this.handleError); | |
}; | |
get = async (config?: AxiosRequestConfig) => { | |
console.log(`API client: get`); | |
return this.axiosInstance | |
.get<T>(this.endpoint, config) | |
.then((response) => response.data) | |
.catch(this.handleError); | |
}; | |
update = async <U>(data?: T, config?: AxiosRequestConfig) => { | |
console.log(`API client: update`); | |
return this.axiosInstance | |
.patch<U>(this.endpoint, data, config) | |
.then((response) => response.data) | |
.catch(this.handleError); | |
}; | |
delete = async (config?: AxiosRequestConfig) => { | |
console.log(`API client: delete`); | |
return this.axiosInstance | |
.delete(this.endpoint, config) | |
.then((response) => response.data) | |
.catch(this.handleError); | |
}; | |
} | |
export default APIClient; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment