StreamFetcher
is a robust utility class designed for making HTTP requests and handling streaming responses.
It supports automatic retries with configurable policies, custom request and response hooks, and cancellation via AbortController
.
Key features include:
- Configurable retry policies with exponential backoff and jitter.
- Streaming
text
andJSON
parsing. - Customizable request and response hooks.
- Abortable requests via
AbortController
. - Fluent API for modifying headers and retry policies. It provides a simple interface for fetching data from a stream, processing it chunk by chunk, and handling potential errors. The class is particularly useful when dealing with large responses or real-time data streams.
<script src="https://cdn.jsdelivr.net/npm/streamfetcher/dist/index.umd.min.js"></script>
<!-- Or via unpkg -->
<script src="https://unpkg.com/streamfetcher"></script>
<!-- Access via global object : window.StreamFetcher -->
- Install / Import
// Node 18+, Deno, Bun, browsers – no extra libs
import { StreamFetcher } from 'streamfetcher';
- One-liner JSON fetch
const { body } = await new StreamFetcher('https://api.example.com/v1/data')
.json<{ id: string; name: string }>();
console.log(body.name);
- Server-sent streaming (e.g. OpenAI chat)
await new StreamFetcher('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: { Authorization: 'Bearer sk-***' },
body: JSON.stringify({ model: 'gpt-3.5-turbo', messages: [...] })
})
.streamText(
({ chunk }) => process.stdout.write(chunk),
AbortSignal.timeout(15000) // optional abort
);
- Retry policy + hooks
const fetcher = new StreamFetcher('/slow-endpoint', {
retryPolicy: { max: 5, baseMs: 300, maxMs: 8000, jitter: true },
onRequest: (url, init) => console.log('➡️', init.method, url),
onResponse: (res) => console.log('⬅️', res.status),
});
setTimeout(() => fetcher.cancel(), 7000); // manual cancel
await fetcher.text().catch(console.error);
- Fluent modifiers (immutable)
const api = new StreamFetcher('/api')
.withRetryPolicy({ max: 2 })
.withHeaders({ 'x-api-key': 'abc123' });
const { body } = await api.json();
- Error handling
try {
await fetcher.json<{ ok: true }>();
} catch (e) {
if (e instanceof HttpError && e.status === 429) {
// rate-limited
} else if (e instanceof NetworkError) {
// offline / DNS failure
}
}
MIT