Skip to content

wutility/StreamFetcher

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

✂ StreamFetcher

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 and JSON 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.
streamfetcher streamfetcher streamfetcher streamfetcher streamfetcher

CDN

<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 -->

Documentation

  1. Install / Import
// Node 18+, Deno, Bun, browsers – no extra libs
import { StreamFetcher } from 'streamfetcher';
  1. One-liner JSON fetch
const { body } = await new StreamFetcher('https://api.example.com/v1/data')
  .json<{ id: string; name: string }>();
console.log(body.name);
  1. 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
  );
  1. 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);
  1. Fluent modifiers (immutable)
const api = new StreamFetcher('/api')
  .withRetryPolicy({ max: 2 })
  .withHeaders({ 'x-api-key': 'abc123' });

const { body } = await api.json();
  1. 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
  }
}

Author

License

MIT

About

`StreamFetcher` is a robust utility class designed for making HTTP requests and handling streaming responses.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published