This module provides a configured Axios instance with request and response interceptors
specifically designed for Spotify API communication. It handles common API scenarios such as
authentication token management, error handling, request retries, and performance monitoring.
Features:
Automatic token refresh on 401 Unauthorized responses
Request queueing during token refresh
Intelligent retry with exponential backoff for failed requests
Request duration tracking for performance monitoring
Comprehensive error handling and logging
Timeout management for API requests
Rate-limiting detection and handling
This module serves as the foundation for all Spotify API communication,
enhancing reliability and reducing boilerplate code throughout the application.
// Helper function to calculate exponential backoff delay constgetBackoffDelay = (retryCount: number): number=> { returnMath.min(1000 * Math.pow(2, retryCount), 10000); };
// Helper function to determine if an error should be retried constshouldRetry = (error: AxiosError): boolean=> { // Retry on network errors if (!error.response) { returntrue; }
conststatus = error.response.status;
// Retry on 5xx server errors if (status >= 500 && status < 600) { returntrue; }
// Retry on 429 (rate limit) errors if (status === 429) { returntrue; }
returnfalse; };
// Create axios instance with interceptors constspotifyAxios = axios.create({ timeout:10000, // 10 second timeout });
// Make sure we always have the latest access token in the request consttoken = getAccessToken(); if (token && config.headers) { config.headers.Authorization = `Bearer ${token}`; // Add debug logging to track token usage saveLog( `Setting Authorization header with token: ${token.substring(0, 5)}...`, "DEBUG", ); }
if (!success) { thrownewError("Failed to refresh token"); }
// Process any queued requests processQueue();
// Get the newly refreshed token constnewToken = getAccessToken(); if (newToken && originalRequest.headers) { // Update the Authorization header with the new token originalRequest.headers.Authorization = `Bearer ${newToken}`; saveLog( `Using new token after refresh: ${newToken.substring(0, 5)}...`, "DEBUG", ); } else { saveLog("No access token available after refresh", "ERROR"); }
// Retry the original request returnspotifyAxios(originalRequest); } catch (refreshError) { // If refresh fails, reject all queued requests processQueue(refreshErrorasError); saveLog("Token refresh failed, authentication required", "ERROR"); returnPromise.reject(refreshError); } finally { isRefreshing = false; } }
// Handle other errors that should be retried if (shouldRetry(error)) { constretryCount = (originalRequest._retryCount || 0) + 1; originalRequest._retryCount = retryCount;
if (retryCount <= MAX_RETRIES) { constdelay = getBackoffDelay(retryCount); saveLog( `Retrying request to ${originalRequest.url} after ${delay}ms (attempt ${retryCount}/${MAX_RETRIES})`, "WARNING", ); awaitnewPromise((resolve) =>setTimeout(resolve, delay)); returnspotifyAxios(originalRequest); } }
// Log error details for debugging saveLog( `API Error: ${status}${error.message} for request to ${originalRequest.url}`, "ERROR", );
Description
Spotify API Request Interceptor Service
This module provides a configured Axios instance with request and response interceptors specifically designed for Spotify API communication. It handles common API scenarios such as authentication token management, error handling, request retries, and performance monitoring.
Features:
This module serves as the foundation for all Spotify API communication, enhancing reliability and reducing boilerplate code throughout the application.
Usage:
Source