Skip to content

Instantly share code, notes, and snippets.

@femicodes
Forked from shreyakupadhyay/BaseAxios.js
Created March 8, 2021 21:59
Show Gist options
  • Select an option

  • Save femicodes/b40351ccaf2bdb2ccd89bbe48e21accf to your computer and use it in GitHub Desktop.

Select an option

Save femicodes/b40351ccaf2bdb2ccd89bbe48e21accf to your computer and use it in GitHub Desktop.
import axios from 'axios';
import { USER_NAME, PASSWORD, REST_END_POINT } from './ApiConstants';
function baseAxios(options) {
const defaultHeaders = {
'Content-Type': 'application/json',
'Accept-Language': options.language ? options.language : 'en',
'lang': options.lang ? options.lang : 'en',
username: USER_NAME,
password: PASSWORD,
...options.extraHeaders
};
const baseUrl = REST_END_POINT;
return axios.create({
baseURL: baseUrl,
timeout: options.timeout || 30000,
headers: defaultHeaders,
})
}
function executeRequest(method, pathname, data, options = {}) {
const body = method === 'get' || !data ? {} : {
data
};
const reqObj = {
method,
url: pathname,
params: options.query,
...body
};
const baseAxiosRequest = baseAxios(options)
return new Promise((resolve, reject) => {
return baseAxiosRequest
.request(reqObj)
.then(res => {
console.log('Axios', res);
resolve(res);
})
.catch(error => {
console.log('Axios', error.response);
reject(error);
});
})
}
export default {
get(pathname, options) {
console.log('BaseApi', options);
return executeRequest('get', pathname, null, options)
},
post(pathname, data, options) {
return executeRequest('post', pathname, data, options)
},
put(pathname, data, options) {
return executeRequest('put', pathname, data, options)
},
delete(pathname, data, options) {
return executeRequest('delete', pathname, data, options)
},
all(promises) {
return axios.all(promises)
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment