Created
April 25, 2020 23:42
-
-
Save shreyakupadhyay/77067a787a51cedb427a8ae3b66f4140 to your computer and use it in GitHub Desktop.
This file contains 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 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
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.