UNPKG

@odyssoft/tmdb

Version:

Unofficial TMDB v3 api wrapper, built using TypeScript and node.js

75 lines (58 loc) 2.41 kB
# Rate Limiting Example This example demonstrates how the rate limiter works with the TMDB library. ```typescript // Custom rate limiter for different use cases import TMDB, { RateLimiter, rateLimiter } from '@odyssoft/tmdb' async function example() { const tmdb = TMDB('your-api-key') console.log('Making 45 rapid requests to test rate limiting...') console.log('Rate limit: 40 requests per 10 seconds') const startTime = Date.now() // Make 45 requests (5 more than the limit) const promises = [] for (let i = 0; i < 45; i++) { promises.push( tmdb.Search.Movies({ query: `test-${i}` }) .then(() => { console.log( `Request ${i + 1} completed at ${Date.now() - startTime}ms` ) }) .catch((err) => { console.log(`Request ${i + 1} failed:`, err.message) }) ) } await Promise.all(promises) const endTime = Date.now() console.log(`All requests completed in ${endTime - startTime}ms`) console.log(`Current rate limiter count: ${rateLimiter.getCurrentCount()}`) } // Access rate limiter directly for monitoring function checkRateLimiter() { console.log('Rate Limiter Status:') console.log(`Current count: ${rateLimiter.getCurrentCount()}`) console.log(`Time until next slot: ${rateLimiter.getTimeUntilNextSlot()}ms`) } const customLimiter = new RateLimiter(10, 5000) // 10 requests per 5 seconds async function customRateLimitExample() { console.log('Using custom rate limiter...') for (let i = 0; i < 15; i++) { await customLimiter.waitForSlot() console.log(`Custom request ${i + 1} allowed`) } } ``` ## Key Features 1. **Automatic Rate Limiting**: All API requests are automatically rate-limited to 40 requests per 10 seconds 2. **Configurable**: You can create custom rate limiters with different limits 3. **Monitoring**: Check current status and time until next available slot 4. **Concurrent Safe**: Handles multiple concurrent requests correctly 5. **Memory Efficient**: Automatically cleans up expired request timestamps ## Rate Limiter Methods - `waitForSlot()`: Wait for an available request slot - `getCurrentCount()`: Get current number of requests in time window - `getTimeUntilNextSlot()`: Get milliseconds until next slot is available - `reset()`: Clear all tracked requests