Last active
November 25, 2023 07:58
-
-
Save gnurgeldiyev/cbca8cc4dd0b4e144d0bd55ff3412ee5 to your computer and use it in GitHub Desktop.
How to get the response time from Axios
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
const axios = require('axios').default | |
const API_BASE_URL = 'https://api.spacexdata.com/v3' | |
const API = axios.create({ | |
baseURL: API_BASE_URL | |
}) | |
/* | |
* setting interceptors to be able | |
* to know response time of the each request | |
*/ | |
API.interceptors.request.use( | |
config => { | |
const newConfig = { ...config } | |
newConfig.metadata = { startTime: new Date() } | |
return newConfig | |
}, | |
error => { | |
return Promise.reject(error) | |
} | |
) | |
API.interceptors.response.use( | |
response => { | |
const newRes = { ...response } | |
newRes.config.metadata.endTime = new Date() | |
newRes.duration = | |
newRes.config.metadata.endTime - newRes.config.metadata.startTime | |
return newRes | |
}, | |
error => { | |
const newError = { ...error } | |
newError.config.metadata.endTime = new Date() | |
newError.duration = | |
newError.config.metadata.endTime - newError.config.metadata.startTime | |
return Promise.reject(newError) | |
} | |
) | |
module.exports = API |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment