refactored out of src packages
This commit is contained in:
38
react-auth/axios.ts
Normal file
38
react-auth/axios.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import axios, { AxiosInstance } from "axios";
|
||||
import { tokenStore } from "./token";
|
||||
|
||||
export function attachAuthInterceptors(client: AxiosInstance) {
|
||||
client.interceptors.request.use((config) => {
|
||||
const token = tokenStore.get();
|
||||
if (token) {
|
||||
if (!config.headers) {
|
||||
(config as any).headers = {};
|
||||
}
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
client.interceptors.response.use(
|
||||
(res) => res,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
tokenStore.clear();
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory for app APIs that need auth
|
||||
*/
|
||||
export function createApiClient(baseURL: string): AxiosInstance {
|
||||
const client = axios.create({
|
||||
baseURL,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
|
||||
attachAuthInterceptors(client);
|
||||
return client;
|
||||
}
|
||||
Reference in New Issue
Block a user