Created
August 13, 2020 16:37
-
-
Save elsetiyawan/5a719c7280f1a8616cbf1bb7f997d47c to your computer and use it in GitHub Desktop.
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 * 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