diff --git a/lib/rest.js b/lib/rest.js index a4a0324..45f9df9 100644 --- a/lib/rest.js +++ b/lib/rest.js @@ -16,6 +16,8 @@ class RestClient { this.baseURL = options.baseURL; this.headers = options.headers; this.restClientConfig = options.restClientConfig; + + addLogger(this.restClientConfig ? this.restClientConfig.debug : false); } buildPath(path) { @@ -112,4 +114,45 @@ method: ${method}`, } } +const addLogger = (debug) => { + if (debug) { + axios.interceptors.request.use((config) => { + const startDate = new Date(); + config.startTime = startDate.valueOf(); + + console.log(`Request method=${config.method} url=${config.url} [${startDate.toISOString()}]`); + + return config; + }); + + axios.interceptors.response.use( + (response) => { + const date = new Date(); + const { status, config } = response; + + console.log( + `Response status=${status} url=${config.url} time=${ + date.valueOf() - config.startTime + }ms [${date.toISOString()}]`, + ); + + return response; + }, + (error) => { + const date = new Date(); + const { response, config } = error; + const status = response ? response.status : null; + + console.log( + `Response ${status ? 'status=' + status : "message='" + error.message + "'"} url=${ + config.url + } time=${date.valueOf() - config.startTime}ms [${date.toISOString()}]`, + ); + + return Promise.reject(error); + }, + ); + } +}; + module.exports = RestClient;