Skip to content

Instantly share code, notes, and snippets.

@b44rd
Created August 7, 2019 14:26
Show Gist options
  • Save b44rd/80d132d1a3b331132209cab923970cc0 to your computer and use it in GitHub Desktop.
Save b44rd/80d132d1a3b331132209cab923970cc0 to your computer and use it in GitHub Desktop.
import axios from 'axios'
import log from 'jsbug'
const randHash = function () {
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5)
}
const get = function (endpoint) {
const id = randHash()
const started = new Date().getTime()
log(`Request #${id} (GET) initiated`)
if (endpoint) {
log(`| Request #${id} (GET) requesting '${endpoint}'`)
return axios.get(endpoint).then((response) => {
log(`Request #${id} (GET) returned successfully (${(new Date().getTime() - started) / 1000} sec)`, { success: true, group: [response] })
return response
}).catch((error) => {
log(`Request #${id} (GET) returned error! (${(new Date().getTime() - started) / 1000} sec)`, { success: false, group: [error] })
return error
})
} else {
throw new Error(`Error! API requests need an endpoint`)
}
}
const post = function (endpoint, params) {
const id = randHash()
const started = new Date().getTime()
log(`Request #${id} (POST) initiated`, { group: [params] })
if (endpoint) {
log(`| Request #${id} (POST) requesting '${endpoint}'`, { group: [params] })
return axios.post(endpoint, params).then((response) => {
log(`Request #${id} (POST) returned successfully (${(new Date().getTime() - started) / 1000} sec)`, { success: true, group: [response] })
return response
}).catch((error) => {
log(`Request #${id} (POST) returned error! (${(new Date().getTime() - started) / 1000} sec)`, { success: false, group: [error] })
return error
})
} else {
throw new Error(`Error! API requests need an endpoint`)
}
}
export {
get,
post
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment