(
url: string,
options: RequestInit = {},
retryOnAuth: boolean = true
)
| 64 | * @returns Response from the fetch request |
| 65 | */ |
| 66 | export const authenticatedFetch = async ( |
| 67 | url: string, |
| 68 | options: RequestInit = {}, |
| 69 | retryOnAuth: boolean = true |
| 70 | ): Promise<Response> => { |
| 71 | // Get current token |
| 72 | const token = localStorage.getItem(LocalStore.accessToken); |
| 73 | |
| 74 | // Setup headers with authentication |
| 75 | const headers = new Headers(options.headers || {}); |
| 76 | if (token) { |
| 77 | headers.set('Authorization', `Bearer ${token}`); |
| 78 | } |
| 79 | |
| 80 | // Make the request |
| 81 | const response = await fetch(url, { |
| 82 | ...options, |
| 83 | headers, |
| 84 | }); |
| 85 | |
| 86 | // If we get a 401 and we should retry, attempt to refresh the token |
| 87 | if (response.status === 401 && retryOnAuth) { |
| 88 | const newToken = await refreshAccessToken(); |
| 89 | |
| 90 | if (newToken) { |
| 91 | // Update the authorization header with the new token |
| 92 | headers.set('Authorization', `Bearer ${newToken}`); |
| 93 | |
| 94 | // Retry the request with the new token |
| 95 | return fetch(url, { |
| 96 | ...options, |
| 97 | headers, |
| 98 | }); |
| 99 | } else { |
| 100 | // If refresh failed, redirect to home/login |
| 101 | if (typeof window !== 'undefined') { |
| 102 | localStorage.removeItem(LocalStore.accessToken); |
| 103 | localStorage.removeItem(LocalStore.refreshToken); |
| 104 | window.location.href = '/'; |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | return response; |
| 110 | }; |
| 111 | |
| 112 | /** |
| 113 | * Processes a streaming response from a server-sent events endpoint |
no test coverage detected