flyonce
v1.0.2
Published
A TypeScript library for single flight operations with caching support
Maintainers
Readme
flyonce
A TypeScript library for single flight operations with caching support. Prevents duplicate function calls and optionally caches results with TTL support.
Features
- Single Flight Pattern: Prevents duplicate function calls for the same key, ensuring only one operation runs at a time
- Smart Caching: Optional TTL-based caching of results with automatic expiration
- Type Safety: Full TypeScript support with generics for complete type safety
- Zero Dependencies: Lightweight with no external dependencies
- High Performance: Optimized for concurrent operations and memory efficiency
- Error Handling: Graceful error propagation and no caching of failed operations
Installation
Choose your preferred package manager:
# npm
npm install flyonce
# yarn
yarn add flyonce
# pnpm
pnpm add flyonce
# bun
bun add flyonceQuick Start
import { SingleFlightWithCache } from 'flyonce';
// Create instance with default TTL (optional)
const sf = new SingleFlightWithCache(5000); // 5 second default TTL
// Basic usage - prevents duplicate API calls
const user = await sf.do('user-123', async () => {
return await fetchUserFromAPI('123');
});
// Multiple concurrent calls to the same key will share the result
const promises = [
sf.do('user-123', () => fetchUserFromAPI('123')),
sf.do('user-123', () => fetchUserFromAPI('123')),
sf.do('user-123', () => fetchUserFromAPI('123'))
];
// Only one API call is made, all promises resolve with the same resultAdvanced Usage
// Custom TTL per operation
const result = await sf.do('user-456', async () => {
return await fetchUserFromAPI('456');
}, 10000); // 10 second TTL
// No caching (single flight only)
const result = await sf.do('temp-data', async () => {
return await expensiveOperation();
}, 0); // TTL = 0 means no caching
// Using with database queries
const users = await sf.do('active-users', async () => {
return await db.query('SELECT * FROM users WHERE active = true');
}, 30000); // Cache for 30 seconds
// Memory management
sf.cleanupExpiredCache(); // Manual cleanup
sf.forget('user-123'); // Remove specific key
sf.clearAll(); // Clear everythingAPI Reference
Constructor
new SingleFlightWithCache(defaultTTL?: number)defaultTTL: Default TTL in milliseconds (default: 0 = no caching)
Methods
do<T>(key: string, fn: () => Promise<T>, ttl?: number): Promise<T>
Execute function with single flight and optional caching.
key: Unique identifier for the operationfn: Async function to executettl: TTL in milliseconds (overrides default)- Returns: Promise that resolves to the function result
forget(key: string): void
Remove cache and cancel inflight operations for a key.
isInFlight(key: string): boolean
Check if an operation is currently running for a key.
isCached(key: string): boolean
Check if a valid cached result exists for a key.
getCached<T>(key: string): T | undefined
Get a cached value if it exists and is not expired.
cleanupExpiredCache(): void
Manually remove expired cache entries.
clearAll(): void
Clear all cache and inflight operations.
getStats(): CacheStats
Get statistics about current cache and inflight operations.
getCacheKeys(): string[]
Get all current cache keys.
getInflightKeys(): string[]
Get all current inflight operation keys.
Use Cases
- API Rate Limiting: Prevent duplicate API calls
- Database Query Optimization: Cache expensive database queries
- Microservices: Reduce redundant service calls
- Data Fetching: Optimize React/Vue component data fetching
- Background Processing: Prevent duplicate background jobs
Performance
flyonce is designed for high-performance scenarios:
- Memory efficient with automatic cleanup
- O(1) lookup time for cache and inflight operations
- Minimal overhead for concurrent operations
- Smart expiration handling
Owner & Contact
Owner: Wahyu Agus Arifin (itpohgero)
Email: [email protected]
Open Source: Available for contributions and collaboration
License
MIT License - feel free to use in your projects!
Contributing
This is an open source project. Contributions, issues, and feature requests are welcome!
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
For questions or support, contact: [email protected]
