Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A better API for making Event Source requests, with all the features of fetch()

License

NotificationsYou must be signed in to change notification settings

Azure/fetch-event-source

This package provides a better API for makingEvent Source requests - also known as server-sent events - with all the features available in theFetch API.

Thedefault browser EventSource API imposes several restrictions on the type of request you're allowed to make: theonly parameters you're allowed to pass in are theurl andwithCredentials, so:

  • You cannot pass in a request body: you have to encode all the information necessary to execute the request inside the URL, which islimited to 2000 characters in most browsers.
  • You cannot pass in custom request headers
  • You can only make GET requests - there is no way to specify another method.
  • If the connection is cut, you don't have any control over the retry strategy: the browser will silently retry for you a few times and then stop, which is not good enough for any sort of robust application.

This library provides an alternate interface for consuming server-sent events, based on the Fetch API. It is fully compatible with theEvent Stream format, so if you already have a server emitting these events, you can consume it just like before. However, you now have greater control over the request and response so:

  • You can use any request method/headers/body, plus all the other functionality exposed by fetch(). You can even provide an alternate fetch() implementation, if the default browser implementation doesn't work for you.
  • You have access to the response object if you want to do some custom validation/processing before parsing the event source. This is useful in case you have API gateways (like nginx) in front of your application server: if the gateway returns an error, you might want to handle it correctly.
  • If the connection gets cut or an error occurs, you have full control over the retry strategy.

In addition, this library also plugs into the browser'sPage Visibility API so the connection closes if the document is hidden (e.g., the user minimizes the window), and automatically retries with the last event ID when it becomes visible again. This reduces the load on your server by not having open connections unnecessarily (but you can opt out of this behavior if you want.)

Install

npm install @microsoft/fetch-event-source

Usage

// BEFORE:constsse=newEventSource('/api/sse');sse.onmessage=(ev)=>{console.log(ev.data);};// AFTER:import{fetchEventSource}from'@microsoft/fetch-event-source';awaitfetchEventSource('/api/sse',{onmessage(ev){console.log(ev.data);}});

You can pass in all theother parameters exposed by the default fetch API, for example:

constctrl=newAbortController();fetchEventSource('/api/sse',{method:'POST',headers:{'Content-Type':'application/json',},body:JSON.stringify({foo:'bar'}),signal:ctrl.signal,});

You can add better error handling, for example:

classRetriableErrorextendsError{}classFatalErrorextendsError{}fetchEventSource('/api/sse',{asynconopen(response){if(response.ok&&response.headers.get('content-type')===EventStreamContentType){return;// everything's good}elseif(response.status>=400&&response.status<500&&response.status!==429){// client-side errors are usually non-retriable:thrownewFatalError();}else{thrownewRetriableError();}},onmessage(msg){// if the server emits an error message, throw an exception// so it gets handled by the onerror callback below:if(msg.event==='FatalError'){thrownewFatalError(msg.data);}},onclose(){// if the server closes the connection unexpectedly, retry:thrownewRetriableError();},onerror(err){if(errinstanceofFatalError){throwerr;// rethrow to stop the operation}else{// do nothing to automatically retry. You can also// return a specific retry interval here.}}});

Compatibility

This library is written in typescript and targets ES2017 features supported by all evergreen browsers (Chrome, Firefox, Safari, Edge.) You might need topolyfill TextDecoder for old Edge (versions < 79), though:

require('fast-text-encoding');

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to aContributor License Agreement (CLA) declaring that you have the right to, and actually do, grant usthe rights to use your contribution. For details, visithttps://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to providea CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructionsprovided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted theMicrosoft Open Source Code of Conduct.For more information see theCode of Conduct FAQ orcontactopencode@microsoft.com with any additional questions or comments.

About

A better API for making Event Source requests, with all the features of fetch()

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp