summaryrefslogtreecommitdiffstats
path: root/src/update.rs
blob: b5b0ba783ebb5c13f747aa8fc39dc8ab398252b4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use std::collections::HashMap;
use serde_json::Value as JsonValue;
use std::future::Future;
use futures::future::BoxFuture;
use log::{ warn, trace };
use crate::client::Client;

pub trait Handler: Send + Sync + 'static {
    fn handle(&self, _: Client, _: JsonValue) -> BoxFuture<'static, ()>;
}

impl<C, F> Handler for C
where C: Send + Sync + 'static + Fn(Client, JsonValue) -> F,
      F: Future<Output = ()> + 'static + Send {
    fn handle(&self, client: Client, req: JsonValue) -> BoxFuture<'static, ()> {
        Box::pin((*self)(client, 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, client: &Client, update: JsonValue) {
        let update_type: &str = update["@type"].as_str().unwrap();
        match self.router.get(update_type) {
            Some(handler) => {
                self.rt.spawn(handler.handle(client.clone(), update));
            },
            None => {
                warn!("no handler for {}", update_type);
                trace!("request was: {}", update);
            },
        }
    }
}