#[cfg(feature = "client")]
use super::HttpClientAsyncFn;
#[cfg(feature = "server")]
use super::{FromStreamingBody, HttpServerAsyncFn, IntoStreamingBody};
use {
super::WsAsyncFn,
serde::{Deserialize, Serialize},
std::io::{Error as IoError, Result as IoResult},
tokio::sync::mpsc::WeakSender,
};
pub trait Binding {
fn unbind(self) -> impl Future<Output = IoResult<()>>;
}
pub struct BaseBinding<Cmd> {
path: String,
command: WeakSender<Cmd>,
}
impl<Cmd> BaseBinding<Cmd> {
pub fn new<P>(path: P, command: WeakSender<Cmd>) -> Self
where
P: AsRef<str>,
{
Self {
path: path.as_ref().to_owned(),
command,
}
}
pub fn get_path(&self) -> &str {
&self.path
}
pub async fn send_command(&self, cmd: Cmd) -> IoResult<()>
where
Cmd: Send + Sync + 'static,
{
let Some(command) = self.command.upgrade() else {
return Err(IoError::other("Command channel is closed."));
};
command.send(cmd).await.map_err(IoError::other)
}
}
pub trait WsRouter<Acc, S = ()> {
type Binding;
fn add_route<F, P, Args, Ret>(
&self,
path: P,
handler: F,
) -> impl Future<Output = IoResult<Self::Binding>>
where
F: WsAsyncFn<Args, Ret, Acc, S>,
Args: for<'a> Deserialize<'a> + Serialize + 'static,
Ret: for<'a> Deserialize<'a> + Serialize + Send + 'static,
P: AsRef<str>;
fn remove_route(binding: Self::Binding) -> impl Future<Output = IoResult<()>>;
}
#[cfg(feature = "client")]
pub trait HttpClientRouter<Acc, S = ()> {
type Binding;
fn add_route<F, P>(&self, path: P, handler: F) -> impl Future<Output = IoResult<Self::Binding>>
where
F: HttpClientAsyncFn<Acc, S>,
P: AsRef<str>;
fn remove_route(binding: Self::Binding) -> impl Future<Output = IoResult<()>>;
}
#[cfg(feature = "server")]
pub trait HttpServerRouter<Acc, S = ()> {
type Binding;
fn add_route<F, P, Body, Ret>(
&self,
path: P,
handler: F,
) -> impl Future<Output = IoResult<Self::Binding>>
where
F: HttpServerAsyncFn<Body, Ret, Acc, S>,
Body: FromStreamingBody,
P: AsRef<str>,
Ret: IntoStreamingBody;
fn remove_route(binding: Self::Binding) -> impl Future<Output = IoResult<()>>;
fn add_default_route<F, Body, Ret>(
&self,
handler: F,
) -> impl Future<Output = IoResult<Self::Binding>>
where
F: HttpServerAsyncFn<Body, Ret, Acc, S>,
Body: FromStreamingBody,
Ret: IntoStreamingBody;
fn remove_default_route() -> impl Future<Output = IoResult<()>>;
}