|
| 1 | +import axios, { AxiosInstance } from 'axios'; |
| 2 | +import React, { createContext, ReactNode, useContext } from 'react'; |
| 3 | +import { AppEnvironment, useAppEnvironment } from '../AppEnvironment'; |
| 4 | +import { getAuthToken, refreshAuth } from '../Auth/Authentication'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Context containing API configuration for the app. |
| 8 | + * Includes authentication and automatic refresh logic. |
| 9 | + */ |
| 10 | +export const ApiContext = createContext<AxiosInstance | undefined>(undefined); |
| 11 | + |
| 12 | +/** |
| 13 | + * Creates API context in the form of a preconfigured Axios instance. |
| 14 | + * Sets base URL to the current app environment, adds interceptors for |
| 15 | + * requests to pass in authorization tokens and to retry with refresh tokens |
| 16 | + * if any 401 errors occur. |
| 17 | + * @param environment AppEnvironment containing the Base URL to use. |
| 18 | + * @returns AxiosInstance for the API context. |
| 19 | + */ |
| 20 | +function createApiContext(environment: AppEnvironment) { |
| 21 | + const instance = axios.create({ |
| 22 | + baseURL: environment.baseUrl, |
| 23 | + }); |
| 24 | + |
| 25 | + instance.interceptors.request.use(async (config) => { |
| 26 | + const token = await getAuthToken(environment); |
| 27 | + console.log(config.baseURL); |
| 28 | + if (token) { |
| 29 | + config.headers.Authorization = `Bearer ${token}`; |
| 30 | + console.log(config.headers.Authorization); |
| 31 | + } |
| 32 | + |
| 33 | + return config; |
| 34 | + }); |
| 35 | + |
| 36 | + instance.interceptors.response.use( |
| 37 | + (response) => response, |
| 38 | + async (error) => { |
| 39 | + if (axios.isAxiosError(error) && error.response?.status === 401) { |
| 40 | + if (!error.config) return Promise.reject(error); |
| 41 | + if (!(await refreshAuth(environment))) return Promise.reject(error); |
| 42 | + const token = await getAuthToken(environment); |
| 43 | + if (token) { |
| 44 | + error.config.headers.Authorization = `Bearer ${token.password}`; |
| 45 | + return axios.request(error.config); |
| 46 | + } |
| 47 | + } |
| 48 | + return Promise.reject(error); |
| 49 | + }, |
| 50 | + ); |
| 51 | + return instance; |
| 52 | +} |
| 53 | + |
| 54 | +function ApiContextProvider({ children }: { children: ReactNode }) { |
| 55 | + const { environment } = useAppEnvironment(); |
| 56 | + const apiContext = createApiContext(environment); |
| 57 | + |
| 58 | + return <ApiContext.Provider value={apiContext}>{children}</ApiContext.Provider>; |
| 59 | +} |
| 60 | + |
| 61 | +export function useApi() { |
| 62 | + const context = useContext(ApiContext); |
| 63 | + if (!context) { |
| 64 | + throw new Error('useApi must be used within an ApiContextProvider'); |
| 65 | + } |
| 66 | + return context; |
| 67 | +} |
| 68 | + |
| 69 | +export default ApiContextProvider; |
0 commit comments