Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/net/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ eventsource = [
'web-sys/Event',
'web-sys/EventTarget',
'web-sys/EventSource',
'web-sys/EventSourceInit',
'web-sys/MessageEvent',
]
# As of now, only implements `AsyncRead` and `AsyncWrite` on `WebSocket`
Expand Down
39 changes: 36 additions & 3 deletions crates/net/src/eventsource/futures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,41 @@ impl fmt::Debug for EventSourceSubscription {
}
}

/// Builder for creating an [`EventSource`] with custom options.
#[derive(Debug, Default, Copy, Clone)]
pub struct EventSourceBuilder {
with_credentials: bool,
}

impl EventSourceBuilder {
/// Create a new builder with default options.
pub fn new() -> Self {
Self::default()
}

/// Set whether cross-origin requests should include credentials.
///
/// When `true`, cookies, authorization headers, or TLS client certificates
/// will be included in cross-origin requests.
///
/// Default is `false`.
pub fn with_credentials(mut self, value: bool) -> Self {
self.with_credentials = value;
self
}

/// Build the EventSource and connect to the given URL.
pub fn build(self, url: &str) -> Result<EventSource, JsError> {
let mut init = web_sys::EventSourceInit::new();
init.with_credentials(self.with_credentials);

let es = web_sys::EventSource::new_with_event_source_init_dict(url, &init)
.map_err(js_to_js_error)?;

Ok(EventSource { es })
}
}

impl EventSource {
/// Establish an EventSource.
///
Expand All @@ -96,9 +131,7 @@ impl EventSource {
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/EventSource/EventSource#exceptions_thrown)
/// to learn more.
pub fn new(url: &str) -> Result<Self, JsError> {
let es = web_sys::EventSource::new(url).map_err(js_to_js_error)?;

Ok(Self { es })
EventSourceBuilder::new().build(url)
}

/// Subscribes to listening for a specific type of event.
Expand Down
Loading