Impl AsyncHandler for SessionDispatcher

This commit is contained in:
Temirkhan Myrzamadi 2020-01-30 01:10:02 +06:00
parent 6d737dabb4
commit c98b53b9a8

View file

@ -34,15 +34,22 @@ mod storage;
use crate::{dispatching::AsyncHandler, Bot}; use crate::{dispatching::AsyncHandler, Bot};
pub use get_chat_id::*; pub use get_chat_id::*;
use std::{future::Future, pin::Pin, sync::Arc};
pub use storage::*; pub use storage::*;
/// A context of a private message handler. /// A context of a private message handler.
pub struct SessionHandlerCtx<'a, Upd, Session> { pub struct SessionHandlerCtx<Upd, Session> {
pub bot: &'a Bot, pub bot: Arc<Bot>,
pub update: Upd, pub update: Upd,
pub session: Session, pub session: Session,
} }
/// A context of a session dispatcher.
pub struct SessionDispatcherCtx<Upd> {
pub bot: Arc<Bot>,
pub update: Upd,
}
/// Continue or terminate a user session. /// Continue or terminate a user session.
#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq)] #[derive(Debug, Copy, Clone, Eq, Hash, PartialEq)]
pub enum SessionState<Session> { pub enum SessionState<Session> {
@ -83,17 +90,25 @@ where
handler, handler,
} }
} }
}
/// Dispatches a single `message` from a private chat. impl<'a, Session, H, Upd> AsyncHandler<SessionDispatcherCtx<Upd>, ()>
pub async fn dispatch<Upd>(&'a self, bot: &'a Bot, update: Upd) for SessionDispatcher<'a, Session, H>
where where
H: AsyncHandler< H: AsyncHandler<SessionHandlerCtx<Upd, Session>, SessionState<Session>>,
SessionHandlerCtx<'a, Upd, Session>,
SessionState<Session>,
>,
Upd: GetChatId, Upd: GetChatId,
Session: Default,
{
/// Dispatches a single `message` from a private chat.
fn handle<'b>(
&'b self,
ctx: SessionDispatcherCtx<Upd>,
) -> Pin<Box<dyn Future<Output = ()> + 'b>>
where
Upd: 'b,
{ {
let chat_id = update.chat_id(); Box::pin(async move {
let chat_id = ctx.update.chat_id();
let session = self let session = self
.storage .storage
@ -104,8 +119,8 @@ where
if let SessionState::Continue(new_session) = self if let SessionState::Continue(new_session) = self
.handler .handler
.handle(SessionHandlerCtx { .handle(SessionHandlerCtx {
bot, bot: ctx.bot,
update, update: ctx.update,
session, session,
}) })
.await .await
@ -122,5 +137,6 @@ where
); );
} }
} }
})
} }
} }