Skip to content

Instantly share code, notes, and snippets.

@elsetiyawan
Created August 13, 2020 16:37
Show Gist options
  • Save elsetiyawan/5a719c7280f1a8616cbf1bb7f997d47c to your computer and use it in GitHub Desktop.
Save elsetiyawan/5a719c7280f1a8616cbf1bb7f997d47c to your computer and use it in GitHub Desktop.
import * as axios from "axios";
import { getCookie, refreshToken } from "./utils";
export default class Api {
constructor() {
this.api_token = null;
this.client = null;
this.api_url = process.env.REACT_APP_API_ENDPOINT;
}
init = () => {
this.api_token = getCookie("ACCESS_TOKEN");
let headers = {
Accept: "application/json",
};
if (this.api_token) {
headers.Authorization = `Bearer ${this.api_token}`;
}
this.client = axios.create({
baseURL: this.api_url,
timeout: 31000,
headers: headers,
});
// HERE IS THE INTERCEPTORS GUYS!!
this.client.interceptors.request.use(
async function (config) {
const newToken = await refreshToken();
config.headers.Authorization = `Bearer ${newToken}`;
return config;
},
);
return this.client;
};
getUserList = (params) => {
return this.init().get("/users", { params: params });
};
addNewUser = (data) => {
return this.init().post("/users", data);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment