Skip to content

Commit

Permalink
RouterBuilderLike helper + fix sub sub router merging
Browse files Browse the repository at this point in the history
  • Loading branch information
oscartbeaumont committed Jan 10, 2023
1 parent 68aa9e1 commit c2d022c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
17 changes: 17 additions & 0 deletions examples/src/bin/merging_routers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use rspc::{Router, RouterBuilderLike};

fn mount_inner() -> impl RouterBuilderLike<()> {
Router::new().query("demo", |t| t(|ctx, _: ()| async move { "Hello World" }))
}

fn mount() -> impl RouterBuilderLike<()> {
Router::<()>::new()
.query("demo", |t| t(|ctx, _: ()| async move { "Hello World" }))
.merge("inner.", mount_inner())
}

fn main() {
let r = Router::<(), ()>::new().merge("java.", mount());

// TODO: Hookup your router to a webserver like Axum or a Tauri desktop app using the Tauri IPC adapter.
}
26 changes: 25 additions & 1 deletion src/router_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,28 @@ pub struct RouterBuilder<
phantom: PhantomData<TMeta>,
}

pub trait RouterBuilderLike<TCtx>
where
TCtx: Send + Sync + 'static,
{
type Middleware: MiddlewareBuilderLike<TCtx> + Send + 'static;

fn expose(self) -> RouterBuilder<TCtx, (), Self::Middleware>;
}

// TODO: Remove `TMeta` from router
impl<TCtx, TMiddleware> RouterBuilderLike<TCtx> for RouterBuilder<TCtx, (), TMiddleware>
where
TCtx: Send + Sync + 'static,
TMiddleware: MiddlewareBuilderLike<TCtx> + Send + 'static,
{
type Middleware = TMiddleware;

fn expose(self) -> RouterBuilder<TCtx, (), Self::Middleware> {
self
}
}

#[allow(clippy::new_without_default, clippy::new_ret_no_self)]
impl<TCtx, TMeta> Router<TCtx, TMeta>
where
Expand Down Expand Up @@ -268,7 +290,7 @@ where
pub fn merge<TNewLayerCtx, TIncomingMiddleware>(
self,
prefix: &'static str,
router: RouterBuilder<TLayerCtx, TMeta, TIncomingMiddleware>,
router: impl RouterBuilderLike<TLayerCtx, Middleware = TIncomingMiddleware>,
) -> RouterBuilder<
TCtx,
TMeta,
Expand All @@ -279,6 +301,8 @@ where
TIncomingMiddleware:
MiddlewareBuilderLike<TLayerCtx, LayerContext = TNewLayerCtx> + Send + 'static,
{
let router = router.expose();

#[allow(clippy::panic)]
if is_valid_procedure_name(prefix) {
panic!(
Expand Down

0 comments on commit c2d022c

Please sign in to comment.