Add server-sent event (for client-side) supports #7584
kingcean
started this conversation in
Ideas / Feature request
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Purpose
Extends following
fromFetchAPI to add supports for server-sent event (a.k.a SSE).Usages
Currently, the API defines following arguments. It contains 2 arguments as same as the ones of
fetchAPI.The current API also has an overload function to extends the second argument which contains a new property
selector.The new property is a handler to get and convert result, e.g. following example (copied from the sample in source code).
My opinion to add SSE supports is to extend the current API. Specifically, we add more overloads of this function to support further scenarios.
So it will get data by SSE mode if the value of property
selectoris stringsse. TheObservableobject returned may occurnextfor multiple times that depends on the SSE item messages received during networking streaming.Further more, the property
selectorcan be other string value for simplifying common scenarios.selectorjsonresponse => response.json()textresponse => response.text()form-dataresponse => response.formData()blobresponse => response.blob()array-bufferresponse => response.arrayBuffer()Implementation
In
~\packages\rxjs\src\internal\observable\dom\fetch.tsfile.export function fromFetch<T>( input: string | Request, initWithSelector: RequestInit & { selector?: (response: Response) => ObservableInput<T>; } = {} ): Observable<Response | T> { + const { selector: originalSelector, ...init } = initWithSelector; + let selector = originalSelector; - const { selector, ...init } = initWithSelector; return new Observable<Response | T>((destination) => { // … some code is omitted here fetch(input, perSubscriberInit) .then((response) => { if (selector) { + if (typeof selector === 'string') { + // add switch-case code here to extend + // the implementation will introduce later + } from(selector(response)).subscribe( operate({ destination, complete: () => { abortable = false; destination.complete(); }, error: handleError, }) ); } else { abortable = false; destination.next(response); destination.complete(); } }) .catch(handleError); // … some code is omitted here }); }The inserted code above is following. It switches the supported
selectorto the corresponding cases.The implementation calls
fetchandresponse.body.getReader()to parse SSE instead ofEventSource, because the latter only supportGETmethod and can't set headers.Beta Was this translation helpful? Give feedback.
All reactions