A lightweight wrapper around the fetch API that automatically dedupes concurrent requests with the same key.
When making multiple identical API calls in quick succession, you often want to cancel previous pending requests to avoid race conditions and unnecessary network traffic. This library solves that problem by providing a simple wrapper around fetch that automatically handles request deduplication.
npm i ddpfetch
import { ddpfetch } from 'ddpfetch'; // Basic usage const response = await ddpfetch('user-data', 'https://api.example.com/users/1'); // With fetch options const response = await ddpfetch('post-data', 'https://api.example.com/posts', { method: 'POST', body: JSON.stringify({ title: 'Hello' }), headers: { 'Content-Type': 'application/json' } }); // Automatic deduping // This will abort the first request and only the second one will complete const promise1 = ddpfetch('same-key', 'https://api.example.com/data'); const promise2 = ddpfetch('same-key', 'https://api.example.com/data'); // Different keys allow concurrent requests const [response1, response2] = await Promise.all([ ddpfetch('key1', 'https://api.example.com/data1'), ddpfetch('key2', 'https://api.example.com/data2') ]);
dedupeKey: A string key that identifies the request. Concurrent requests with the same key will cancel previous pending requests.input: The resource URL or Request object (same as fetch)init: Fetch options (same as fetch)- Returns: A Promise that resolves to the Response (same as fetch)
The library uses AbortController signals internally to cancel previous pending requests with the same dedupeKey. When a new request is made with the same key as a pending request:
- The previous request is aborted
- The new request is initiated
- The request is automatically cleaned up from memory when completed
Run the test suite:
npm testRun with coverage:
npm run test:coverage
ISC
Michael Di Prisco cadienvan@gmail.com