mirror of
https://github.com/fafhrd91/actix-web
synced 2024-11-24 00:21:08 +01:00
Allow to set/override app data on scope level
This commit is contained in:
parent
df08baf67f
commit
45c05978b0
@ -1,5 +1,11 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.0-beta.4] - 2019-05-xx
|
||||||
|
|
||||||
|
### Add
|
||||||
|
|
||||||
|
* Allow to set/override app data on scope level
|
||||||
|
|
||||||
### Changes
|
### Changes
|
||||||
|
|
||||||
* `App::configure` take an `FnOnce` instead of `Fn`
|
* `App::configure` take an `FnOnce` instead of `Fn`
|
||||||
|
@ -95,8 +95,8 @@ where
|
|||||||
/// web::get().to(index)));
|
/// web::get().to(index)));
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn data<U: Into<Data<U>> + 'static>(mut self, data: U) -> Self {
|
pub fn data<U: 'static>(mut self, data: U) -> Self {
|
||||||
self.data.push(Box::new(data.into()));
|
self.data.push(Box::new(Data::new(data)));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -31,7 +31,7 @@ pub struct AppService {
|
|||||||
Option<Guards>,
|
Option<Guards>,
|
||||||
Option<Rc<ResourceMap>>,
|
Option<Rc<ResourceMap>>,
|
||||||
)>,
|
)>,
|
||||||
route_data: Rc<Vec<Box<DataFactory>>>,
|
service_data: Rc<Vec<Box<DataFactory>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppService {
|
impl AppService {
|
||||||
@ -39,12 +39,12 @@ impl AppService {
|
|||||||
pub(crate) fn new(
|
pub(crate) fn new(
|
||||||
config: AppConfig,
|
config: AppConfig,
|
||||||
default: Rc<HttpNewService>,
|
default: Rc<HttpNewService>,
|
||||||
route_data: Rc<Vec<Box<DataFactory>>>,
|
service_data: Rc<Vec<Box<DataFactory>>>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
AppService {
|
AppService {
|
||||||
config,
|
config,
|
||||||
default,
|
default,
|
||||||
route_data,
|
service_data,
|
||||||
root: true,
|
root: true,
|
||||||
services: Vec::new(),
|
services: Vec::new(),
|
||||||
}
|
}
|
||||||
@ -75,7 +75,7 @@ impl AppService {
|
|||||||
default: self.default.clone(),
|
default: self.default.clone(),
|
||||||
services: Vec::new(),
|
services: Vec::new(),
|
||||||
root: false,
|
root: false,
|
||||||
route_data: self.route_data.clone(),
|
service_data: self.service_data.clone(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -90,11 +90,11 @@ impl AppService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Set global route data
|
/// Set global route data
|
||||||
pub fn set_route_data(&self, extensions: &mut Extensions) -> bool {
|
pub fn set_service_data(&self, extensions: &mut Extensions) -> bool {
|
||||||
for f in self.route_data.iter() {
|
for f in self.service_data.iter() {
|
||||||
f.create(extensions);
|
f.create(extensions);
|
||||||
}
|
}
|
||||||
!self.route_data.is_empty()
|
!self.service_data.is_empty()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Register http service
|
/// Register http service
|
||||||
@ -192,8 +192,8 @@ impl ServiceConfig {
|
|||||||
/// by using `Data<T>` extractor where `T` is data type.
|
/// by using `Data<T>` extractor where `T` is data type.
|
||||||
///
|
///
|
||||||
/// This is same as `App::data()` method.
|
/// This is same as `App::data()` method.
|
||||||
pub fn data<S: Into<Data<S>> + 'static>(&mut self, data: S) -> &mut Self {
|
pub fn data<S: 'static>(&mut self, data: S) -> &mut Self {
|
||||||
self.data.push(Box::new(data.into()));
|
self.data.push(Box::new(Data::new(data)));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -93,12 +93,6 @@ impl<T> Clone for Data<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> From<T> for Data<T> {
|
|
||||||
fn from(data: T) -> Self {
|
|
||||||
Data::new(data)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: 'static> FromRequest for Data<T> {
|
impl<T: 'static> FromRequest for Data<T> {
|
||||||
type Config = ();
|
type Config = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -135,6 +129,7 @@ impl<T: 'static> DataFactory for Data<T> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
use crate::http::StatusCode;
|
use crate::http::StatusCode;
|
||||||
use crate::test::{block_on, init_service, TestRequest};
|
use crate::test::{block_on, init_service, TestRequest};
|
||||||
|
@ -407,7 +407,7 @@ where
|
|||||||
}
|
}
|
||||||
// custom app data storage
|
// custom app data storage
|
||||||
if let Some(ref mut ext) = self.data {
|
if let Some(ref mut ext) = self.data {
|
||||||
config.set_route_data(ext);
|
config.set_service_data(ext);
|
||||||
}
|
}
|
||||||
config.register_service(rdef, guards, self, None)
|
config.register_service(rdef, guards, self, None)
|
||||||
}
|
}
|
||||||
|
73
src/scope.rs
73
src/scope.rs
@ -2,7 +2,7 @@ use std::cell::RefCell;
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_http::Response;
|
use actix_http::{Extensions, Response};
|
||||||
use actix_router::{ResourceDef, ResourceInfo, Router};
|
use actix_router::{ResourceDef, ResourceInfo, Router};
|
||||||
use actix_service::boxed::{self, BoxedNewService, BoxedService};
|
use actix_service::boxed::{self, BoxedNewService, BoxedService};
|
||||||
use actix_service::{
|
use actix_service::{
|
||||||
@ -11,6 +11,7 @@ use actix_service::{
|
|||||||
use futures::future::{ok, Either, Future, FutureResult};
|
use futures::future::{ok, Either, Future, FutureResult};
|
||||||
use futures::{Async, IntoFuture, Poll};
|
use futures::{Async, IntoFuture, Poll};
|
||||||
|
|
||||||
|
use crate::data::Data;
|
||||||
use crate::dev::{AppService, HttpServiceFactory};
|
use crate::dev::{AppService, HttpServiceFactory};
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
use crate::guard::Guard;
|
use crate::guard::Guard;
|
||||||
@ -61,6 +62,7 @@ type BoxedResponse = Either<
|
|||||||
pub struct Scope<T = ScopeEndpoint> {
|
pub struct Scope<T = ScopeEndpoint> {
|
||||||
endpoint: T,
|
endpoint: T,
|
||||||
rdef: String,
|
rdef: String,
|
||||||
|
data: Option<Extensions>,
|
||||||
services: Vec<Box<ServiceFactory>>,
|
services: Vec<Box<ServiceFactory>>,
|
||||||
guards: Vec<Box<Guard>>,
|
guards: Vec<Box<Guard>>,
|
||||||
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
||||||
@ -74,6 +76,7 @@ impl Scope {
|
|||||||
Scope {
|
Scope {
|
||||||
endpoint: ScopeEndpoint::new(fref.clone()),
|
endpoint: ScopeEndpoint::new(fref.clone()),
|
||||||
rdef: path.to_string(),
|
rdef: path.to_string(),
|
||||||
|
data: None,
|
||||||
guards: Vec::new(),
|
guards: Vec::new(),
|
||||||
services: Vec::new(),
|
services: Vec::new(),
|
||||||
default: Rc::new(RefCell::new(None)),
|
default: Rc::new(RefCell::new(None)),
|
||||||
@ -117,6 +120,39 @@ where
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set or override application data. Application data could be accessed
|
||||||
|
/// by using `Data<T>` extractor where `T` is data type.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// use std::cell::Cell;
|
||||||
|
/// use actix_web::{web, App};
|
||||||
|
///
|
||||||
|
/// struct MyData {
|
||||||
|
/// counter: Cell<usize>,
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn index(data: web::Data<MyData>) {
|
||||||
|
/// data.counter.set(data.counter.get() + 1);
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn main() {
|
||||||
|
/// let app = App::new().service(
|
||||||
|
/// web::scope("/app")
|
||||||
|
/// .data(MyData{ counter: Cell::new(0) })
|
||||||
|
/// .service(
|
||||||
|
/// web::resource("/index.html").route(
|
||||||
|
/// web::get().to(index)))
|
||||||
|
/// );
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub fn data<U: 'static>(mut self, data: U) -> Self {
|
||||||
|
if self.data.is_none() {
|
||||||
|
self.data = Some(Extensions::new());
|
||||||
|
}
|
||||||
|
self.data.as_mut().unwrap().insert(Data::new(data));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Register http service.
|
/// Register http service.
|
||||||
///
|
///
|
||||||
/// This is similar to `App's` service registration.
|
/// This is similar to `App's` service registration.
|
||||||
@ -241,6 +277,7 @@ where
|
|||||||
Scope {
|
Scope {
|
||||||
endpoint,
|
endpoint,
|
||||||
rdef: self.rdef,
|
rdef: self.rdef,
|
||||||
|
data: self.data,
|
||||||
guards: self.guards,
|
guards: self.guards,
|
||||||
services: self.services,
|
services: self.services,
|
||||||
default: self.default,
|
default: self.default,
|
||||||
@ -308,7 +345,7 @@ where
|
|||||||
InitError = (),
|
InitError = (),
|
||||||
> + 'static,
|
> + 'static,
|
||||||
{
|
{
|
||||||
fn register(self, config: &mut AppService) {
|
fn register(mut self, config: &mut AppService) {
|
||||||
// update default resource if needed
|
// update default resource if needed
|
||||||
if self.default.borrow().is_none() {
|
if self.default.borrow().is_none() {
|
||||||
*self.default.borrow_mut() = Some(config.default_service());
|
*self.default.borrow_mut() = Some(config.default_service());
|
||||||
@ -322,8 +359,14 @@ where
|
|||||||
|
|
||||||
let mut rmap = ResourceMap::new(ResourceDef::root_prefix(&self.rdef));
|
let mut rmap = ResourceMap::new(ResourceDef::root_prefix(&self.rdef));
|
||||||
|
|
||||||
|
// custom app data storage
|
||||||
|
if let Some(ref mut ext) = self.data {
|
||||||
|
config.set_service_data(ext);
|
||||||
|
}
|
||||||
|
|
||||||
// complete scope pipeline creation
|
// complete scope pipeline creation
|
||||||
*self.factory_ref.borrow_mut() = Some(ScopeFactory {
|
*self.factory_ref.borrow_mut() = Some(ScopeFactory {
|
||||||
|
data: self.data.take().map(|data| Rc::new(data)),
|
||||||
default: self.default.clone(),
|
default: self.default.clone(),
|
||||||
services: Rc::new(
|
services: Rc::new(
|
||||||
cfg.into_services()
|
cfg.into_services()
|
||||||
@ -355,6 +398,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct ScopeFactory {
|
pub struct ScopeFactory {
|
||||||
|
data: Option<Rc<Extensions>>,
|
||||||
services: Rc<Vec<(ResourceDef, HttpNewService, RefCell<Option<Guards>>)>>,
|
services: Rc<Vec<(ResourceDef, HttpNewService, RefCell<Option<Guards>>)>>,
|
||||||
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
||||||
}
|
}
|
||||||
@ -388,6 +432,7 @@ impl NewService for ScopeFactory {
|
|||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
default: None,
|
default: None,
|
||||||
|
data: self.data.clone(),
|
||||||
default_fut,
|
default_fut,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -397,6 +442,7 @@ impl NewService for ScopeFactory {
|
|||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct ScopeFactoryResponse {
|
pub struct ScopeFactoryResponse {
|
||||||
fut: Vec<CreateScopeServiceItem>,
|
fut: Vec<CreateScopeServiceItem>,
|
||||||
|
data: Option<Rc<Extensions>>,
|
||||||
default: Option<HttpService>,
|
default: Option<HttpService>,
|
||||||
default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>,
|
default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>,
|
||||||
}
|
}
|
||||||
@ -460,6 +506,7 @@ impl Future for ScopeFactoryResponse {
|
|||||||
router
|
router
|
||||||
});
|
});
|
||||||
Ok(Async::Ready(ScopeService {
|
Ok(Async::Ready(ScopeService {
|
||||||
|
data: self.data.clone(),
|
||||||
router: router.finish(),
|
router: router.finish(),
|
||||||
default: self.default.take(),
|
default: self.default.take(),
|
||||||
_ready: None,
|
_ready: None,
|
||||||
@ -471,6 +518,7 @@ impl Future for ScopeFactoryResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct ScopeService {
|
pub struct ScopeService {
|
||||||
|
data: Option<Rc<Extensions>>,
|
||||||
router: Router<HttpService, Vec<Box<Guard>>>,
|
router: Router<HttpService, Vec<Box<Guard>>>,
|
||||||
default: Option<HttpService>,
|
default: Option<HttpService>,
|
||||||
_ready: Option<(ServiceRequest, ResourceInfo)>,
|
_ready: Option<(ServiceRequest, ResourceInfo)>,
|
||||||
@ -499,6 +547,9 @@ impl Service for ScopeService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if let Some((srv, _info)) = res {
|
if let Some((srv, _info)) = res {
|
||||||
|
if let Some(ref data) = self.data {
|
||||||
|
req.set_data_container(data.clone());
|
||||||
|
}
|
||||||
Either::A(srv.call(req))
|
Either::A(srv.call(req))
|
||||||
} else if let Some(ref mut default) = self.default {
|
} else if let Some(ref mut default) = self.default {
|
||||||
Either::A(default.call(req))
|
Either::A(default.call(req))
|
||||||
@ -953,4 +1004,22 @@ mod tests {
|
|||||||
HeaderValue::from_static("0001")
|
HeaderValue::from_static("0001")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_override_data() {
|
||||||
|
let mut srv = init_service(App::new().data(1usize).service(
|
||||||
|
web::scope("app").data(10usize).route(
|
||||||
|
"/t",
|
||||||
|
web::get().to(|data: web::Data<usize>| {
|
||||||
|
assert_eq!(*data, 10);
|
||||||
|
let _ = data.clone();
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
|
||||||
|
let req = TestRequest::with_uri("/app/t").to_request();
|
||||||
|
let resp = call_service(&mut srv, req);
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user