### Install Rate Keeper Package Source: https://github.com/melon-dog/rate-keeper/blob/main/README.md Installs the rate-keeper package using npm. This is the initial step to use the library in your project. ```bash npm install rate-keeper ``` -------------------------------- ### Limit Queue Size with Reject Policy using RateKeeper Source: https://context7.com/melon-dog/rate-keeper/llms.txt This example demonstrates how to limit the queue size of function calls using RateKeeper. When the queue reaches its maximum capacity, new entries are rejected with an error. This is useful for preventing overload when a strict limit is required. ```typescript import RateKeeper, { DropPolicy } from "rate-keeper"; function logAnalyticsEvent(event: string): void { console.log(`Analytics: ${event}`); } const rateLimitedAnalytics = RateKeeper( logAnalyticsEvent, 100, { id: 3001, maxQueueSize: 3, dropPolicy: DropPolicy.Reject } ); // Queue up events rateLimitedAnalytics("Page View"); // Executes immediately rateLimitedAnalytics("Button Click"); // Queued (position 1) rateLimitedAnalytics("Form Submit"); // Queued (position 2) rateLimitedAnalytics("Video Play"); // Queued (position 3) // Queue is full, next call is rejected rateLimitedAnalytics("Download Start") .catch(error => { console.error(error.message); // "Queue is at max capacity." }); // Output: // Analytics: Page View (immediate) // Analytics: Button Click (after 100ms) // Analytics: Form Submit (after 200ms) // Analytics: Video Play (after 300ms) // Queue is at max capacity. ``` -------------------------------- ### Limit Queue Size with DropOldest Policy using RateKeeper Source: https://context7.com/melon-dog/rate-keeper/llms.txt This example shows how to manage queue size with the `DropOldest` policy in RateKeeper. When the queue is full, the oldest pending item is removed to make space for the new one. This ensures that the most recent actions are prioritized. ```typescript import RateKeeper, { DropPolicy } from "rate-keeper"; interface CacheUpdate { key: string; value: any; } function updateCache(update: CacheUpdate): void { console.log(`Cache update: ${update.key} = ${update.value}`); } const rateLimitedCacheUpdate = RateKeeper( updateCache, 50, { id: 4001, maxQueueSize: 4, dropPolicy: DropPolicy.DropOldest } ); // Queue updates rateLimitedCacheUpdate({ key: "user:1", value: "Alice" }); // Executes immediately rateLimitedCacheUpdate({ key: "user:2", value: "Bob" }); // Queued position 1 rateLimitedCacheUpdate({ key: "user:3", value: "Charlie" }); // Queued position 2 rateLimitedCacheUpdate({ key: "user:4", value: "David" }); // Queued position 3 rateLimitedCacheUpdate({ key: "user:5", value: "Eve" }); // Queued position 4 // New entry drops oldest queued item (user:2 is removed) rateLimitedCacheUpdate({ key: "user:6", value: "Frank" }); // Output: // Cache update: user:1 = Alice (immediate) // Cache update: user:3 = Charlie (after 50ms) - user:2 was dropped // Cache update: user:4 = David (after 100ms) // Cache update: user:5 = Eve (after 150ms) // Cache update: user:6 = Frank (after 200ms) ``` -------------------------------- ### Cancel Queued Actions with RateKeeper Source: https://context7.com/melon-dog/rate-keeper/llms.txt This example demonstrates how to cancel pending operations managed by RateKeeper. The `cancel` method can be called on the returned promise for a queued function call to prevent it from executing. This is useful for user-initiated cancellations or timeout scenarios. ```typescript import RateKeeper, { CancelablePromise } from "rate-keeper"; function processPayment(amount: number, orderId: string): string { console.log(`Processing $${amount} for order ${orderId}`); return `Payment processed: ${orderId}`; } const rateLimitedPayment = RateKeeper(processPayment, 1000); // Queue multiple payments const payment1 = rateLimitedPayment(100, "ORD-001"); // Executes immediately const payment2 = rateLimitedPayment(200, "ORD-002"); // Queued const payment3 = rateLimitedPayment(300, "ORD-003"); // Queued // User cancels second order before it processes payment2.cancel(new Error("Order cancelled by user")); // Handle cancellation payment2.catch(error => { console.error(`Payment failed: ${error.message}`); }); // Wait for remaining payments await Promise.allSettled([payment1, payment2, payment3]); // Output: // Processing $100 for order ORD-001 (immediate) // Payment failed: Order cancelled by user (immediate) // Processing $300 for order ORD-003 (after 1000ms) - ORD-002 skipped ``` -------------------------------- ### Handling Promises with Rate Keeper (JavaScript) Source: https://github.com/melon-dog/rate-keeper/blob/main/README.md Demonstrates how functions wrapped by RateKeeper return promises. This allows for straightforward asynchronous handling of the results after the rate-limited function has executed. ```javascript import RateKeeper from "rate-keeper"; function logMessage(newLog) { console.log(newLog); return newLog; } const safeLogger = RateKeeper(logMessage, 500); // Minimum of 500ms between calls. safeLogger("Hello World 1").then((result) => { //... }); ``` -------------------------------- ### Implement Complex API Rate Limiting with TypeScript Source: https://context7.com/melon-dog/rate-keeper/llms.txt This snippet demonstrates how to use the rate-keeper library to manage rate limits for multiple API clients (Twitter and GitHub) concurrently. It shows setting up different rate limits for each API and coordinating their usage within an application function. Dependencies include the 'rate-keeper' library and browser's 'fetch' API. ```typescript import RateKeeper, { DropPolicy } from "rate-keeper"; // API client configuration const TWITTER_QUEUE = 5001; const GITHUB_QUEUE = 5002; // Twitter API: 300 requests per 15 minutes = ~3 requests per second const postTweet = RateKeeper( async (content: string) => { const response = await fetch('https://api.twitter.com/2/tweets', { method: 'POST', headers: { 'Authorization': 'Bearer TOKEN' }, body: JSON.stringify({ text: content }) }); return response.json(); }, 333, // 333ms between calls ≈ 3 per second { id: TWITTER_QUEUE, maxQueueSize: 50, dropPolicy: DropPolicy.DropOldest } ); // GitHub API: 5000 requests per hour = ~83 per minute const fetchGitHubRepo = RateKeeper( async (owner: string, repo: string) => { const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`, { headers: { 'Authorization': 'token GITHUB_TOKEN' } }); return response.json(); }, 720, // 720ms between calls ≈ 83 per minute { id: GITHUB_QUEUE } ); // Usage in application async function syncRepositories(repos: Array<{ owner: string; name: string }>) { const results = []; for (const repo of repos) { try { const data = await fetchGitHubRepo(repo.owner, repo.name); results.push(data); // Tweet about successful sync await postTweet(`Synced ${repo.owner}/${repo.name} - ${data.stargazers_count} stars`); } catch (error) { console.error(`Failed to sync ${repo.owner}/${repo.name}:`, error); } } return results; } // Process 10 repositories with automatic rate limiting const repos = [ { owner: "microsoft", name: "typescript" }, { owner: "facebook", name: "react" }, // ... 8 more repos ]; syncRepositories(repos); // Automatically rate-limited across both APIs ``` -------------------------------- ### Rate Limiting with Queue Options (JavaScript) Source: https://github.com/melon-dog/rate-keeper/blob/main/README.md Shows advanced queue configuration using RateKeeper, including `maxQueueSize` and `dropPolicy`. The `DropOldest` policy ensures that when the queue is full, the oldest task is removed to accommodate new ones. ```javascript import RateKeeper, { DropPolicy } from "rate-keeper"; function logMessage(newLog) { console.log(newLog); return newLog; } const queueID = 2002; const loggerWithLimit = RateKeeper(logMessage, 500, { id: queueID, maxQueueSize: 2, dropPolicy: DropPolicy.DropOldest, // Removes the oldest task when the queue is full }); loggerWithLimit("Message 0"); // Processed. loggerWithLimit("Message 1"); // Added to queue loggerWithLimit("Message 2"); // Added to queue loggerWithLimit("Message 3"); // "Message 1" is dropped, "Message 3" added // Logs will be processed with a 500ms interval ``` -------------------------------- ### Basic Rate Limiting with Rate Keeper (JavaScript) Source: https://github.com/melon-dog/rate-keeper/blob/main/README.md Demonstrates the basic usage of RateKeeper to limit the execution rate of a function. A minimum delay of 500ms is enforced between calls to the wrapped function. ```javascript import RateKeeper from "rate-keeper"; function logMessage(newLog) { console.log(newLog); return newLog; } const safeLogger = RateKeeper(logMessage, 500); // Minimum of 500ms between calls. safeLogger("Message 1"); safeLogger("Message 2"); safeLogger("Message 3"); ``` -------------------------------- ### Rate Limiting with Shared Queues (JavaScript) Source: https://github.com/melon-dog/rate-keeper/blob/main/README.md Illustrates how to use RateKeeper to manage shared queues by providing an `id`. Functions with the same `id` will share a rate-limited queue, while functions without an `id` or with different `id`s will have independent queues. ```javascript import RateKeeper from "rate-keeper"; function logMessage(newLog) { console.log(newLog); return newLog; } const queueID = 1001; const logger1 = RateKeeper(logMessage, 500, { id: queueID }); // Shared queue with logger2 const logger2 = RateKeeper(logMessage, 500, { id: queueID }); // Shared queue with logger1 const logger3 = RateKeeper(logMessage, 500); // Independent queue logger1("Queue Message 1"); logger2("Queue Message 2"); logger3("Independent Message"); ``` -------------------------------- ### Promise Handling with Rate Limiting in TypeScript Source: https://context7.com/melon-dog/rate-keeper/llms.txt Demonstrates how rate-limited functions in TypeScript return cancelable promises. This allows for asynchronous handling using `async/await` or `.then()` and chaining multiple operations with `Promise.all`, while respecting the defined rate limits. ```typescript import RateKeeper from "rate-keeper"; async function fetchUserData(userId: number): Promise<{ id: number; name: string }> { return { id: userId, name: `User ${userId}` }; } const rateLimitedFetch = RateKeeper(fetchUserData, 1000); // Use async/await const user1 = await rateLimitedFetch(101); console.log(user1); // { id: 101, name: "User 101" } // Use .then() rateLimitedFetch(102) .then(user => { console.log(`Fetched: ${user.name}`); return user; }) .catch(error => { console.error("Failed:", error.message); }); // Chain multiple operations const results = await Promise.all([ rateLimitedFetch(103), rateLimitedFetch(104), rateLimitedFetch(105) ]); console.log(results); // Array of 3 user objects, spaced 1000ms apart ``` -------------------------------- ### Canceling Actions with Rate Keeper (JavaScript) Source: https://github.com/melon-dog/rate-keeper/blob/main/README.md Shows how to cancel a scheduled action before it is executed. The `cancel()` method can be called on the promise returned by the rate-limited function to prevent its execution. ```javascript import RateKeeper from "rate-keeper"; function logMessage(newLog) { console.log(newLog); return newLog; } const safeLogger = RateKeeper(logMessage, 500); // Minimum of 500ms between calls. safeLogger("Message 1"); const message2 = safeLogger("Message 2"); safeLogger("Message 3"); message2.cancel(); ``` -------------------------------- ### Basic Rate Limiting with TypeScript Source: https://context7.com/melon-dog/rate-keeper/llms.txt Wraps a function to enforce a minimum interval between calls using TypeScript. It queues subsequent calls and executes them sequentially after the interval has passed. Ideal for controlling the frequency of operations like sending emails. ```typescript import RateKeeper from "rate-keeper"; // Original function function sendEmailNotification(recipient: string, message: string): string { console.log(`Sending email to ${recipient}: ${message}`); return `Email sent to ${recipient}`; } // Wrap with rate limiting (500ms minimum between calls) const rateLimitedEmail = RateKeeper(sendEmailNotification, 500); // Usage - calls are automatically queued and executed with 500ms intervals rateLimitedEmail("user1@example.com", "Welcome!"); rateLimitedEmail("user2@example.com", "Thank you!"); rateLimitedEmail("user3@example.com", "Update available!"); // Output: // Sending email to user1@example.com: Welcome! (immediate) // Sending email to user2@example.com: Thank you! (after 500ms) // Sending email to user3@example.com: Update available! (after 1000ms) ``` -------------------------------- ### Shared Queue Management with TypeScript Source: https://context7.com/melon-dog/rate-keeper/llms.txt Illustrates how to manage rate limiting across multiple functions using shared queue IDs in TypeScript. Functions with the same ID share a rate limit, while functions with different IDs operate independently, allowing for coordinated API call frequency control. ```typescript import RateKeeper from "rate-keeper"; const SHOPIFY_QUEUE = 1001; const STRIPE_QUEUE = 2001; // Multiple functions sharing the same Shopify API rate limit const getShopifyOrder = RateKeeper( (orderId: string) => fetch(`/shopify/orders/${orderId}`).then(r => r.json()), 200, { id: SHOPIFY_QUEUE } ); const updateShopifyInventory = RateKeeper( (sku: string, quantity: number) => fetch(`/shopify/inventory/${sku}`, { method: 'PUT', body: JSON.stringify({ quantity }) }), 200, { id: SHOPIFY_QUEUE } ); // Independent Stripe API with different rate limit const createStripeCharge = RateKeeper( (amount: number, token: string) => fetch('/stripe/charges', { method: 'POST', body: JSON.stringify({ amount, token }) }), 100, { id: STRIPE_QUEUE } ); // Execution: Shopify calls share queue (200ms intervals), Stripe is independent (100ms intervals) getShopifyOrder("ORDER-123"); // Executes immediately updateShopifyInventory("SKU-456", 50); // Queued, executes after 200ms (Shopify queue) createStripeCharge(1999, "tok_visa"); // Executes immediately (separate queue) getShopifyOrder("ORDER-789"); // Queued, executes after 400ms (Shopify queue) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.