|
| 1 | +import { LocalStore } from '@/lib/storage'; |
| 2 | +import { client } from '@/lib/client'; |
| 3 | +import { REFRESH_TOKEN_MUTATION } from '@/graphql/mutations/auth'; |
| 4 | +import { gql } from '@apollo/client'; |
| 5 | + |
| 6 | +// Prevent multiple simultaneous refresh attempts |
| 7 | +let isRefreshing = false; |
| 8 | +let refreshPromise: Promise<string | null> | null = null; |
| 9 | + |
| 10 | +/** |
| 11 | + * Refreshes the access token using the refresh token |
| 12 | + * @returns Promise that resolves to the new token or null if refresh failed |
| 13 | + */ |
| 14 | +export const refreshAccessToken = async (): Promise<string | null> => { |
| 15 | + // If a refresh is already in progress, return that promise |
| 16 | + if (isRefreshing && refreshPromise) { |
| 17 | + return refreshPromise; |
| 18 | + } |
| 19 | + |
| 20 | + isRefreshing = true; |
| 21 | + refreshPromise = (async () => { |
| 22 | + try { |
| 23 | + const refreshToken = localStorage.getItem(LocalStore.refreshToken); |
| 24 | + if (!refreshToken) { |
| 25 | + return null; |
| 26 | + } |
| 27 | + |
| 28 | + // Use Apollo client to refresh the token |
| 29 | + const result = await client.mutate({ |
| 30 | + mutation: REFRESH_TOKEN_MUTATION, |
| 31 | + variables: { refreshToken }, |
| 32 | + }); |
| 33 | + |
| 34 | + if (result.data?.refreshToken?.accessToken) { |
| 35 | + const newAccessToken = result.data.refreshToken.accessToken; |
| 36 | + const newRefreshToken = |
| 37 | + result.data.refreshToken.refreshToken || refreshToken; |
| 38 | + |
| 39 | + localStorage.setItem(LocalStore.accessToken, newAccessToken); |
| 40 | + localStorage.setItem(LocalStore.refreshToken, newRefreshToken); |
| 41 | + |
| 42 | + console.log('Token refreshed successfully'); |
| 43 | + return newAccessToken; |
| 44 | + } |
| 45 | + |
| 46 | + return null; |
| 47 | + } catch (error) { |
| 48 | + console.error('Error refreshing token:', error); |
| 49 | + return null; |
| 50 | + } finally { |
| 51 | + isRefreshing = false; |
| 52 | + refreshPromise = null; |
| 53 | + } |
| 54 | + })(); |
| 55 | + |
| 56 | + return refreshPromise; |
| 57 | +}; |
| 58 | + |
| 59 | +/** |
| 60 | + * Fetch wrapper that handles authentication and token refresh |
| 61 | + * @param url The URL to fetch |
| 62 | + * @param options Fetch options |
| 63 | + * @param retryOnAuth Whether to retry on 401 errors (default: 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 |
| 114 | + * @param response Fetch Response object (must be a streaming response) |
| 115 | + * @param onChunk Optional callback to process each chunk as it arrives |
| 116 | + * @returns Promise with the full aggregated content |
| 117 | + */ |
| 118 | +export const processStreamResponse = async ( |
| 119 | + response: Response, |
| 120 | + onChunk?: (chunk: string) => void |
| 121 | +): Promise<string> => { |
| 122 | + if (!response.body) { |
| 123 | + throw new Error('Response has no body'); |
| 124 | + } |
| 125 | + |
| 126 | + const reader = response.body.getReader(); |
| 127 | + let fullContent = ''; |
| 128 | + let isStreamDone = false; |
| 129 | + |
| 130 | + try { |
| 131 | + // More explicit condition than while(true) |
| 132 | + while (!isStreamDone) { |
| 133 | + const { done, value } = await reader.read(); |
| 134 | + |
| 135 | + if (done) { |
| 136 | + isStreamDone = true; |
| 137 | + continue; |
| 138 | + } |
| 139 | + |
| 140 | + const text = new TextDecoder().decode(value); |
| 141 | + const lines = text.split('\n\n'); |
| 142 | + |
| 143 | + for (const line of lines) { |
| 144 | + if (line.startsWith('data: ')) { |
| 145 | + const data = line.slice(6).trim(); |
| 146 | + |
| 147 | + // Additional exit condition |
| 148 | + if (data === '[DONE]') { |
| 149 | + isStreamDone = true; |
| 150 | + break; |
| 151 | + } |
| 152 | + |
| 153 | + try { |
| 154 | + const parsed = JSON.parse(data); |
| 155 | + if (parsed.content) { |
| 156 | + fullContent += parsed.content; |
| 157 | + if (onChunk) { |
| 158 | + onChunk(parsed.content); |
| 159 | + } |
| 160 | + } |
| 161 | + } catch (e) { |
| 162 | + console.error('Error parsing SSE data:', e); |
| 163 | + } |
| 164 | + } |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + return fullContent; |
| 169 | + } catch (error) { |
| 170 | + console.error('Error reading stream:', error); |
| 171 | + throw error; |
| 172 | + } finally { |
| 173 | + // Ensure we clean up the reader if we exit due to an error |
| 174 | + if (!isStreamDone) { |
| 175 | + reader |
| 176 | + .cancel() |
| 177 | + .catch((e) => console.error('Error cancelling reader:', e)); |
| 178 | + } |
| 179 | + } |
| 180 | +}; |
| 181 | + |
| 182 | +export default authenticatedFetch; |
0 commit comments