add `Route::wrap`

This commit is contained in:
Rob Ede 2022-04-08 12:49:11 +01:00
parent de9e41484a
commit 783b3f7a8f
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
1 changed files with 23 additions and 2 deletions

View File

@ -1,15 +1,17 @@
use std::{mem, rc::Rc}; use std::{mem, rc::Rc};
use actix_http::Method; use actix_http::{body::MessageBody, Method};
use actix_service::{ use actix_service::{
apply,
boxed::{self, BoxService}, boxed::{self, BoxService},
fn_service, Service, ServiceFactory, ServiceFactoryExt, fn_service, Service, ServiceFactory, ServiceFactoryExt, Transform,
}; };
use futures_core::future::LocalBoxFuture; use futures_core::future::LocalBoxFuture;
use crate::{ use crate::{
guard::{self, Guard}, guard::{self, Guard},
handler::{handler_service, Handler}, handler::{handler_service, Handler},
middleware::Compat,
service::{BoxedHttpServiceFactory, ServiceRequest, ServiceResponse}, service::{BoxedHttpServiceFactory, ServiceRequest, ServiceResponse},
Error, FromRequest, HttpResponse, Responder, Error, FromRequest, HttpResponse, Responder,
}; };
@ -35,6 +37,25 @@ impl Route {
} }
} }
#[doc(alias = "middleware")]
#[doc(alias = "use")] // nodejs terminology
pub fn wrap<M, B>(self, mw: M) -> Route
where
M: Transform<
BoxService<ServiceRequest, ServiceResponse, Error>,
ServiceRequest,
Response = ServiceResponse<B>,
Error = Error,
InitError = (),
> + 'static,
B: MessageBody + 'static,
{
Route {
service: boxed::factory(apply(Compat::new(mw), self.service)),
guards: self.guards,
}
}
pub(crate) fn take_guards(&mut self) -> Vec<Box<dyn Guard>> { pub(crate) fn take_guards(&mut self) -> Vec<Box<dyn Guard>> {
mem::take(Rc::get_mut(&mut self.guards).unwrap()) mem::take(Rc::get_mut(&mut self.guards).unwrap())
} }