Skip to content

Instantly share code, notes, and snippets.

@shreyakupadhyay
Created April 25, 2020 23:42
Show Gist options
  • Save shreyakupadhyay/77067a787a51cedb427a8ae3b66f4140 to your computer and use it in GitHub Desktop.
Save shreyakupadhyay/77067a787a51cedb427a8ae3b66f4140 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)
},
}
@shreyakupadhyay
Copy link
Author

I have used this code from an online source, I could not find it later. If anyone of you finds the reference please add the comment below and I will add the reference to the post.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment