I have the following axis service:
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'Authorization': 'Bearer ' token}
});
I need conditionally pass isAdmin from outside for being able to switch the API URL here. How can be it achieved.
CodePudding user response:
We could pass in the value into the constructor, and pass it to the initInstance method, then return the URL contingent on the value of isAdmin.
class AxiosService {
// ...
constructor(isAdmin = false) {
this.initInstance(isAdmin);
}
initInstance(isAdmin) {
this.axiosInstance = axios.create({
baseURL: isAdmin ? '/api/admin/v1' : '/api/v1',
timeout: 5000
});
// ...
}
// ...
}
To use these, we'd now go...
const axiosService = new AxiosService(true); // admin url will be used
CodePudding user response:
You can use multiple instances for each baseURL and call the instance by isAdmin condition. However, you can config the defaults that will be applied to every request.
import axios from "axios";
/* default config for each request */
axios.defaults.headers['Authorization'] = 'Bearer ' token;
axios.defaults.timeout = 1000;
const adminAxios = axios.create({
baseURL: 'https://some-domain.com/api/'
});
const nonAdminAxios = axios.create({
baseURL: 'https://other-some-domain.com/api/'
});
const getInstance = (isAdmin) => isAdmin ? adminAxios : nonAdminAxios;
