Change event handling to return multiple events

Signed-off-by: trivernis <trivernis@protonmail.com>
pull/1/head
trivernis 4 years ago
parent 0ee8d691c7
commit eec5e698d3
Signed by: Trivernis
GPG Key ID: DFFFCC2C7A02DB45

@ -1,7 +1,7 @@
[package] [package]
name = "vented" name = "vented"
description = "Event driven encrypted tcp communicaton" description = "Event driven encrypted tcp communicaton"
version = "0.5.0" version = "0.6.0"
authors = ["trivernis <trivernis@protonmail.com>"] authors = ["trivernis <trivernis@protonmail.com>"]
edition = "2018" edition = "2018"
readme = "README.md" readme = "README.md"

@ -33,21 +33,17 @@ impl EventHandler {
} }
/// Handles a single event /// Handles a single event
pub fn handle_event(&mut self, event: Event) -> Option<Event> { pub fn handle_event(&mut self, event: Event) -> Vec<Event> {
let mut response_events = Vec::new();
if let Some(handlers) = self.event_handlers.get(&event.name) { if let Some(handlers) = self.event_handlers.get(&event.name) {
let mut event = Some(event);
for handler in handlers { for handler in handlers {
if let Some(e) = handler(event.unwrap()) { if let Some(e) = handler(event.clone()) {
event = Some(e); response_events.push(e);
} else {
event = None;
break;
} }
} }
event
} else {
None
} }
response_events
} }
} }

@ -148,9 +148,8 @@ impl VentedServer {
} }
/// Adds a handler for the given event. /// Adds a handler for the given event.
/// The event returned by the handler is returned to the server. /// The event returned by the handler is returned to the sender.
/// If there is more than one handler, the response will be piped to the next handler. /// Multiple handlers can be registered for an event.
/// The oder is by order of insertion. The first registered handler will be executed first.
pub fn on<F: 'static>(&mut self, event_name: &str, handler: F) pub fn on<F: 'static>(&mut self, event_name: &str, handler: F)
where where
F: Fn(Event) -> Option<Event> + Send + Sync, F: Fn(Event) -> Option<Event> + Send + Sync,
@ -299,7 +298,7 @@ impl VentedServer {
) -> VentedResult<()> { ) -> VentedResult<()> {
while let Ok(mut event) = stream.read() { while let Ok(mut event) = stream.read() {
event.origin = Some(stream.receiver_node().clone()); event.origin = Some(stream.receiver_node().clone());
if let Some(response) = event_handler.lock().handle_event(event) { for response in event_handler.lock().handle_event(event) {
stream.send(response)? stream.send(response)?
} }
} }

@ -153,7 +153,7 @@ impl VentedServer {
let event_handler = Arc::clone(&event_handler); let event_handler = Arc::clone(&event_handler);
move || { move || {
let response = event_handler.lock().handle_event(event); let response = event_handler.lock().handle_event(event);
let event = response.map(|mut value| { let event = response.first().cloned().map(|mut value| {
Event::with_payload( Event::with_payload(
REDIRECT_EVENT, REDIRECT_EVENT,
&RedirectPayload::new( &RedirectPayload::new(

Loading…
Cancel
Save