From decad3adca84fd8abcbd3315678fe8cbcabb9f9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Minelli?= <michael@minelli.me> Date: Fri, 2 Jun 2023 18:38:05 +0200 Subject: [PATCH] Add axios interceptors --- NodeApp/src/managers/HttpManager.ts | 55 +++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 NodeApp/src/managers/HttpManager.ts diff --git a/NodeApp/src/managers/HttpManager.ts b/NodeApp/src/managers/HttpManager.ts new file mode 100644 index 0000000..62c787a --- /dev/null +++ b/NodeApp/src/managers/HttpManager.ts @@ -0,0 +1,55 @@ +import axios, { AxiosRequestHeaders } from 'axios'; +import Config from '../Config/Config'; +import SessionManager from './SessionManager'; +import FormData from 'form-data'; + + +class HttpManager { + private static _instance: HttpManager; + + public static get instance(): HttpManager { + if ( !HttpManager._instance ) { + HttpManager._instance = new HttpManager(); + } + + return HttpManager._instance; + } + + registerAxiosInterceptor() { + this.registerRequestInterceptor(); + this.registerResponseInterceptor(); + } + + private registerRequestInterceptor() { + axios.interceptors.request.use((config) => { + if ( config.data instanceof FormData ) { + config.headers = { ...config.headers, ...(config.data as FormData).getHeaders() } as AxiosRequestHeaders; + } + + if ( SessionManager.isLogged && config.url && config.url.indexOf(Config.apiURL) !== -1 ) { + config.headers.Authorization = 'BEARER ' + SessionManager.token; + } + + return config; + }); + } + + private registerResponseInterceptor() { + axios.interceptors.response.use((response) => { + + if ( response.data && response.data.token ) { + SessionManager.token = response.data.token; + } + + return response; + }, (error) => { + if ( error.response.status === 401 ) { + + } + }); + } +} + + +export default HttpManager.instance; + -- GitLab