Forked from sabljakovich/axios-interceptors-log-response-time-example.js
Created
January 31, 2021 10:17
-
-
Save alexh225/9ba4ef3ca4f415e556013e708be6df38 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