use core::future::Future;
use worker::{console_debug, Method, Request, Response, Result, RouteContext, Router};
pub trait Params {
fn param_(&self, key: &str) -> Option<&String>;
}
impl<D> Params for RouteContext<D> {
fn param_(&self, key: &str) -> Option<&String> {
self.param(key)
}
}
#[doc(hidden)]
#[allow(clippy::module_name_repetitions)]
pub trait RouteFactory<D> {
fn register(self, router: Router<'_, D>) -> Router<'_, D>;
}
pub trait Configure<D> {
fn configure<F: RouteFactory<D>>(self, f: F) -> Self;
}
impl<D> Configure<D> for Router<'_, D> {
fn configure<F: RouteFactory<D>>(self, f: F) -> Self {
f.register(self)
}
}
pub trait Service {
fn service<F: FnOnce(Self) -> Self>(self, f: F) -> Self
where
Self: Sized;
}
impl<D> Service for Router<'_, D> {
fn service<F: FnOnce(Self) -> Self>(self, f: F) -> Self {
f(self)
}
}
type Handler<D, U> = fn(Request, RouteContext<D>) -> U;
#[doc(hidden)]
pub trait AddHandler<'a, D> {
fn register(
self,
pattern: &str,
method: Method,
sync_handler: Handler<D, Result<Response>>,
) -> Self;
fn register_async<U: Future<Output = Result<Response>> + 'a>(
self,
pattern: &str,
method: Method,
async_handler: Handler<D, U>,
) -> Self;
}
impl<'a, D: 'a> AddHandler<'a, D> for Router<'a, D> {
fn register(
self,
pattern: &str,
method: Method,
sync_handler: Handler<D, Result<Response>>,
) -> Self {
match method {
Method::Head => self.head(pattern, sync_handler),
Method::Get => self.get(pattern, sync_handler),
Method::Post => self.post(pattern, sync_handler),
Method::Put => self.put(pattern, sync_handler),
Method::Patch => self.patch(pattern, sync_handler),
Method::Delete => self.delete(pattern, sync_handler),
Method::Options => self.options(pattern, sync_handler),
_ => {
console_debug!("{:?} is not supported.", method);
panic!()
}
}
}
fn register_async<U: Future<Output = Result<Response>> + 'a>(
self,
pattern: &str,
method: Method,
async_handler: Handler<D, U>,
) -> Self {
match method {
Method::Head => self.head_async(pattern, async_handler),
Method::Get => self.get_async(pattern, async_handler),
Method::Post => self.post_async(pattern, async_handler),
Method::Put => self.put_async(pattern, async_handler),
Method::Patch => self.patch_async(pattern, async_handler),
Method::Delete => self.delete_async(pattern, async_handler),
Method::Options => self.options_async(pattern, async_handler),
_ => {
console_debug!("{:?} is not supported.", method);
panic!()
}
}
}
}