Skip to content

Instantly share code, notes, and snippets.

@andreswebs
Forked from EnetoJara/api.config.ts
Created May 2, 2020 15:10
Show Gist options
  • Save andreswebs/33c5bdf6c4091c17d5e1463ad95c61af to your computer and use it in GitHub Desktop.
Save andreswebs/33c5bdf6c4091c17d5e1463ad95c61af to your computer and use it in GitHub Desktop.
import * as qs from "qs";
import { PathLike } from "fs";
export const apiConfig = {
returnRejectedPromiseOnError: true,
withCredentials: true,
timeout: 30000,
baseURL: "https://jsonplaceholder.typicode.com/",
headers: {
common: {
"Cache-Control": "no-cache, no-store, must-revalidate",
Pragma: "no-cache",
"Content-Type": "application/json",
Accept: "application/json",
},
},
paramsSerializer: (params: PathLike) => qs.stringify(params, { indices: false }),
}
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
export class Api {
private api: AxiosInstance;
public constructor (config: AxiosRequestConfig) {
this.api = axios.create(config);
// this middleware is been called right before the http request is made.
this.api.interceptors.request.use((param: AxiosRequestConfig) => ({
...param
}));
// this middleware is been called right before the response is get it by the method that triggers the request
this.api.interceptors.response.use((param: AxiosResponse) => ({
...param
}));
}
public getUri (config?: AxiosRequestConfig): string {
return this.api.getUri(config);
}
public request<T, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R> {
return this.api.request(config);
}
public get<T, R = AxiosResponse<T>> (url: string, config?: AxiosRequestConfig): Promise<R> {
return this.api.get(url, config);
}
public delete<T, R = AxiosResponse<T>> (url: string, config?: AxiosRequestConfig): Promise<R> {
return this.api.delete(url, config);
}
public head<T, R = AxiosResponse<T>> (url: string, config?: AxiosRequestConfig): Promise<R> {
return this.api.head(url, config);
}
public post<T, R = AxiosResponse<T>> (url: string, data?: string, config?: AxiosRequestConfig): Promise<R> {
return this.api.post(url, data, config);
}
public put<T, R = AxiosResponse<T>> (url: string, data?: string, config?: AxiosRequestConfig): Promise<R> {
return this.api.put(url, data, config);
}
public patch<T, R = AxiosResponse<T>> (url: string, data?: string, config?: AxiosRequestConfig): Promise<R> {
return this.api.patch(url, data, config);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment