Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sabljakovich/3431d67ba38741c6ebb3077adc777d4d to your computer and use it in GitHub Desktop.
Save sabljakovich/3431d67ba38741c6ebb3077adc777d4d to your computer and use it in GitHub Desktop.
// npm i axios
const axios = require('axios').default;
axios.interceptors.request.use( x => {
// to avoid overwriting if another interceptor
// already defined the same object (meta)
x.meta = x.meta || {}
x.meta.requestStartedAt = new Date().getTime();
return x;
})
axios.interceptors.response.use( x => {
console.log(`Execution time for: ${x.config.url} - ${ new Date().getTime() - x.config.meta.requestStartedAt} ms`)
return x;
},
// Handle 4xx & 5xx responses
x => {
console.error(`Execution time for: ${x.config.url} - ${new Date().getTime() - x.config.meta.requestStartedAt} ms`)
throw x;
}
)
const run = async () => {
// SUCCESS call
await axios.get('https://jsonplaceholder.typicode.com/todos/1', { headers: { 'x-trace-id': '1234-1234'} })
.then( x => x.data)
.then( x => console.log(x))
// FAILED call - 404
// await axios.get('https://jsonplaceholder.typicode.com/todos12/1', { headers: { 'x-trace-id': '1234-1234'} })
// .then( x => x.data)
// .then( x => console.log(x))
}
run().then( x => console.log('Completed'))
@talentedandrew
Copy link

Thanks. Very helpful

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