Skip to content

Instantly share code, notes, and snippets.

@dclawson
Created April 1, 2021 14:39
Show Gist options
  • Save dclawson/832b5b3f88e948cd6cfac9fc93f57824 to your computer and use it in GitHub Desktop.
Save dclawson/832b5b3f88e948cd6cfac9fc93f57824 to your computer and use it in GitHub Desktop.
import axios from 'axios'
const baseRequest = async (options) => {
const onSuccess = (response) => {
console.debug('Request Success:', response)
return httpResponse(200, response)
}
const onError = (error) => {
let { response, request, message } = error
if (response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error(response.status, response.statusText)
} else if (request) {
// The request was made but no response was received
// `request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.error('No Response Error:', request)
} else {
// Something happened in setting up the request that triggered an Error
console.error('Request Error:', message)
}
return httpResponse(response?.status, message)
}
const httpResponse = (status = 402, message) => {
return {
status,
message,
}
}
const makeRequest = async () => {
try {
const response = await axios({
timeout: 25000,
headers: {
'content-type': 'application/json',
},
...options,
})
const data = await response.data
return onSuccess(data)
} catch (error) {
return onError(error)
}
}
return makeRequest()
}
export default baseRequest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment