Skip to content

Commit

Permalink
chore(router): resources add with_handler
Browse files Browse the repository at this point in the history
  • Loading branch information
fundon committed Oct 28, 2022
1 parent 91a25d4 commit 9f1c8d7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
11 changes: 10 additions & 1 deletion viz-router/src/resources.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
//! Resource
use viz_core::{
BoxHandler, Handler, HandlerExt, IntoResponse, Method, Request, Response, Result, Transform,
BoxHandler, Handler, HandlerExt, IntoResponse, Method, Next, Request, Response, Result,
Transform,
};

use crate::Route;
Expand Down Expand Up @@ -190,6 +191,14 @@ impl Resources {
{
self.map_handler(|handler| t.transform(handler).boxed())
}

/// Adds a middleware for the resources.
pub fn with_handler<F>(self, f: F) -> Self
where
F: Handler<Next<Request, BoxHandler>, Output = Result<Response>> + Clone,
{
self.map_handler(|handler| handler.around(f.clone()).boxed())
}
}

impl IntoIterator for Resources {
Expand Down
13 changes: 10 additions & 3 deletions viz-router/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,8 @@ mod tests {
use viz_core::{
async_trait,
types::{Params, RouteInfo},
Body, Error, Handler, HandlerExt, IntoResponse, Method, Request, RequestExt, Response,
ResponseExt, Result, StatusCode, Transform,
Body, Error, Handler, HandlerExt, IntoResponse, Method, Next, Request, RequestExt,
Response, ResponseExt, Result, StatusCode, Transform,
};

use crate::{any, get, Resources, Route, Router, Tree};
Expand Down Expand Up @@ -266,10 +266,17 @@ mod tests {
Ok(Response::new(("delete".to_string() + &items).into()))
}

async fn middle<H>((req, h): Next<Request, H>) -> Result<Response>
where
H: Handler<Request, Output = Result<Response>> + Clone,
{
h.call(req).await
}

let users = Resources::default()
.named("user")
.index(index)
.create(create.before(|r: Request| async { Ok(r) }))
.create(create.before(|r: Request| async { Ok(r) }).around(middle))
.show(show)
.update(update)
.destroy(delete)
Expand Down

0 comments on commit 9f1c8d7

Please sign in to comment.