Forked from sabljakovich/axios-interceptors-log-response-time-example.js
Created
August 23, 2021 23:55
-
-
Save JonathonJulian/80b1e7082f660109c383492c2238cdd6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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