Created
September 23, 2020 00:28
-
-
Save dejanvasic85/7c2d445d2fee57f4dd674f224c64cd2e to your computer and use it in GitHub Desktop.
Axios Http Client with Logging
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
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'; | |
import tracingLogger from '../../logging/tracingLogger'; | |
interface RequestConfig extends AxiosRequestConfig { | |
metadata: { | |
startTime: number; | |
}; | |
} | |
const createHttpClient = (baseURL: string, defaultHeaders: any = {}): AxiosInstance => { | |
const client = axios.create({ | |
baseURL, | |
headers: { ...defaultHeaders, 'Cache-Control': 'no-cache' }, | |
}); | |
client.interceptors.request.use( | |
(config: RequestConfig) => { | |
const logger = tracingLogger(); | |
logger.info({ url: config.url }, 'HttpClient Request starting'); | |
config.metadata = { startTime: Date.now() }; | |
return config; | |
}, | |
(err) => Promise.reject(err), | |
); | |
client.interceptors.response.use( | |
(resp) => { | |
const config = resp.config as RequestConfig; | |
const latency = Date.now() - config.metadata.startTime; | |
const logger = tracingLogger(); | |
logger.info({ url: config.url, latency, statusCode: resp.status }, 'HttpClient Request completed'); | |
return resp; | |
}, | |
(err) => Promise.reject(err), | |
); | |
return client; | |
}; | |
export default createHttpClient; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment