Created
March 24, 2020 17:31
-
-
Save sabljakovich/3431d67ba38741c6ebb3077adc777d4d 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
// 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')) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. Very helpful