summaryrefslogtreecommitdiffstats
path: root/src/update.rs
diff options
context:
space:
mode:
authorsyn <isaqtm@gmail.com>2020-05-19 20:54:45 +0300
committersyn <isaqtm@gmail.com>2020-05-19 20:54:45 +0300
commitc89b1acb6e5d5755dc79c1f5643c915624a4c4c3 (patch)
tree2b51d52df177db1b14eb6666236a131356e5452f /src/update.rs
downloadpert-c89b1acb6e5d5755dc79c1f5643c915624a4c4c3.tar.gz
Some kind of working code
Diffstat (limited to 'src/update.rs')
-rw-r--r--src/update.rs40
1 files changed, 40 insertions, 0 deletions
diff --git a/src/update.rs b/src/update.rs
new file mode 100644
index 0000000..a6884e3
--- /dev/null
+++ b/src/update.rs
@@ -0,0 +1,40 @@
+use std::collections::HashMap;
+use json::JsonValue;
+use std::future::Future;
+use futures::future::BoxFuture;
+
+pub trait Handler: Send + Sync + 'static {
+ fn handle(&self, _: JsonValue) -> BoxFuture<'static, ()>;
+}
+
+impl<C, F> Handler for C
+where C: Send + Sync + 'static + Fn(JsonValue) -> F,
+ F: Future<Output = ()> + 'static + Send {
+ fn handle(&self, req: JsonValue) -> BoxFuture<'static, ()> {
+ Box::pin((*self)(req))
+ }
+}
+
+pub struct UpdateRouter {
+ router: HashMap<String, Box<dyn Handler>>,
+ rt: tokio::runtime::Handle,
+}
+
+impl UpdateRouter {
+ pub fn new(rt: tokio::runtime::Handle) -> Self {
+ Self {
+ router: HashMap::new(),
+ rt: rt
+ }
+ }
+ pub fn add_handler<H: Handler>(&mut self, update_type: &str, handler: H) {
+ self.router.insert(update_type.to_owned(), Box::new(handler));
+ }
+
+ pub fn dispatch(&self, update: JsonValue) {
+ let update_type: &str = update["@type"].as_str().unwrap();
+ self.router.get(update_type)
+ .and_then(|handler| { self.rt.spawn(handler.handle(update)); Some(()) })
+ .or_else(|| { println!("handler not found"); Some(()) });
+ }
+}