Skip to content

Commit

Permalink
Preventing Rate Limiting errors. (#1528)
Browse files Browse the repository at this point in the history
Cache successful responses in memory
Return cached data when hitting rate limits
Maintain the existing React cache functionality
Provide better error handling
  • Loading branch information
smian1 authored Dec 12, 2024
2 parents ea3e6d7 + eedffba commit 980d239
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions frontend/src/lib/api/apps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ import { cache } from 'react';
import envConfig from '@/src/constants/envConfig';
import { Plugin, PluginStat } from '@/src/app/apps/components/types';

// Store last successful response in memory
let lastSuccessfulResponse: Plugin[] | null = null;

/**
* Cached fetch utility for approved apps
* Uses React's cache() for route segment caching
* Includes runtime caching for rate limit handling
*/
export const getApprovedApps = cache(async () => {
try {
Expand All @@ -16,13 +20,24 @@ export const getApprovedApps = cache(async () => {
);

if (!response.ok) {
if (response.status === 429 && lastSuccessfulResponse) {
console.log('Rate limit hit, using cached data');
return lastSuccessfulResponse;
}
throw new Error(`Failed to fetch apps: ${response.statusText}`);
}

const plugins = (await response.json()) as Plugin[];
// Store successful response in memory
lastSuccessfulResponse = plugins;
return plugins;
} catch (error) {
console.error('Error fetching approved apps:', error);
// Return cached data for any network errors if available
if (lastSuccessfulResponse) {
console.log('Error occurred, using cached data');
return lastSuccessfulResponse;
}
throw error;
}
});
Expand Down

0 comments on commit 980d239

Please sign in to comment.