Skip to content

Commit

Permalink
Allow to set/override app data on scope level
Browse files Browse the repository at this point in the history
  • Loading branch information
fafhrd91 committed May 12, 2019
1 parent df08baf commit 45c0597
Show file tree
Hide file tree
Showing 6 changed files with 90 additions and 20 deletions.
6 changes: 6 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changes

## [1.0.0-beta.4] - 2019-05-xx

### Add

* Allow to set/override app data on scope level

### Changes

* `App::configure` take an `FnOnce` instead of `Fn`
Expand Down
4 changes: 2 additions & 2 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ where
/// web::get().to(index)));
/// }
/// ```
pub fn data<U: Into<Data<U>> + 'static>(mut self, data: U) -> Self {
self.data.push(Box::new(data.into()));
pub fn data<U: 'static>(mut self, data: U) -> Self {
self.data.push(Box::new(Data::new(data)));
self
}

Expand Down
18 changes: 9 additions & 9 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,20 @@ pub struct AppService {
Option<Guards>,
Option<Rc<ResourceMap>>,
)>,
route_data: Rc<Vec<Box<DataFactory>>>,
service_data: Rc<Vec<Box<DataFactory>>>,
}

impl AppService {
/// Crate server settings instance
pub(crate) fn new(
config: AppConfig,
default: Rc<HttpNewService>,
route_data: Rc<Vec<Box<DataFactory>>>,
service_data: Rc<Vec<Box<DataFactory>>>,
) -> Self {
AppService {
config,
default,
route_data,
service_data,
root: true,
services: Vec::new(),
}
Expand Down Expand Up @@ -75,7 +75,7 @@ impl AppService {
default: self.default.clone(),
services: Vec::new(),
root: false,
route_data: self.route_data.clone(),
service_data: self.service_data.clone(),
}
}

Expand All @@ -90,11 +90,11 @@ impl AppService {
}

/// Set global route data
pub fn set_route_data(&self, extensions: &mut Extensions) -> bool {
for f in self.route_data.iter() {
pub fn set_service_data(&self, extensions: &mut Extensions) -> bool {
for f in self.service_data.iter() {
f.create(extensions);
}
!self.route_data.is_empty()
!self.service_data.is_empty()
}

/// Register http service
Expand Down Expand Up @@ -192,8 +192,8 @@ impl ServiceConfig {
/// by using `Data<T>` extractor where `T` is data type.
///
/// This is same as `App::data()` method.
pub fn data<S: Into<Data<S>> + 'static>(&mut self, data: S) -> &mut Self {
self.data.push(Box::new(data.into()));
pub fn data<S: 'static>(&mut self, data: S) -> &mut Self {
self.data.push(Box::new(Data::new(data)));
self
}

Expand Down
7 changes: 1 addition & 6 deletions src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
type Config = ();
type Error = Error;
Expand Down Expand Up @@ -135,6 +129,7 @@ impl<T: 'static> DataFactory for Data<T> {
#[cfg(test)]
mod tests {
use actix_service::Service;
use std::sync::Mutex;

use crate::http::StatusCode;
use crate::test::{block_on, init_service, TestRequest};
Expand Down
2 changes: 1 addition & 1 deletion src/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ where
}
// custom app data storage
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)
}
Expand Down
73 changes: 71 additions & 2 deletions src/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;

use actix_http::Response;
use actix_http::{Extensions, Response};
use actix_router::{ResourceDef, ResourceInfo, Router};
use actix_service::boxed::{self, BoxedNewService, BoxedService};
use actix_service::{
Expand All @@ -11,6 +11,7 @@ use actix_service::{
use futures::future::{ok, Either, Future, FutureResult};
use futures::{Async, IntoFuture, Poll};

use crate::data::Data;
use crate::dev::{AppService, HttpServiceFactory};
use crate::error::Error;
use crate::guard::Guard;
Expand Down Expand Up @@ -61,6 +62,7 @@ type BoxedResponse = Either<
pub struct Scope<T = ScopeEndpoint> {
endpoint: T,
rdef: String,
data: Option<Extensions>,
services: Vec<Box<ServiceFactory>>,
guards: Vec<Box<Guard>>,
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
Expand All @@ -74,6 +76,7 @@ impl Scope {
Scope {
endpoint: ScopeEndpoint::new(fref.clone()),
rdef: path.to_string(),
data: None,
guards: Vec::new(),
services: Vec::new(),
default: Rc::new(RefCell::new(None)),
Expand Down Expand Up @@ -117,6 +120,39 @@ where
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.
///
/// This is similar to `App's` service registration.
Expand Down Expand Up @@ -241,6 +277,7 @@ where
Scope {
endpoint,
rdef: self.rdef,
data: self.data,
guards: self.guards,
services: self.services,
default: self.default,
Expand Down Expand Up @@ -308,7 +345,7 @@ where
InitError = (),
> + 'static,
{
fn register(self, config: &mut AppService) {
fn register(mut self, config: &mut AppService) {
// update default resource if needed
if self.default.borrow().is_none() {
*self.default.borrow_mut() = Some(config.default_service());
Expand All @@ -322,8 +359,14 @@ where

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
*self.factory_ref.borrow_mut() = Some(ScopeFactory {
data: self.data.take().map(|data| Rc::new(data)),
default: self.default.clone(),
services: Rc::new(
cfg.into_services()
Expand Down Expand Up @@ -355,6 +398,7 @@ where
}

pub struct ScopeFactory {
data: Option<Rc<Extensions>>,
services: Rc<Vec<(ResourceDef, HttpNewService, RefCell<Option<Guards>>)>>,
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
}
Expand Down Expand Up @@ -388,6 +432,7 @@ impl NewService for ScopeFactory {
})
.collect(),
default: None,
data: self.data.clone(),
default_fut,
}
}
Expand All @@ -397,6 +442,7 @@ impl NewService for ScopeFactory {
#[doc(hidden)]
pub struct ScopeFactoryResponse {
fut: Vec<CreateScopeServiceItem>,
data: Option<Rc<Extensions>>,
default: Option<HttpService>,
default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>,
}
Expand Down Expand Up @@ -460,6 +506,7 @@ impl Future for ScopeFactoryResponse {
router
});
Ok(Async::Ready(ScopeService {
data: self.data.clone(),
router: router.finish(),
default: self.default.take(),
_ready: None,
Expand All @@ -471,6 +518,7 @@ impl Future for ScopeFactoryResponse {
}

pub struct ScopeService {
data: Option<Rc<Extensions>>,
router: Router<HttpService, Vec<Box<Guard>>>,
default: Option<HttpService>,
_ready: Option<(ServiceRequest, ResourceInfo)>,
Expand Down Expand Up @@ -499,6 +547,9 @@ impl Service for ScopeService {
});

if let Some((srv, _info)) = res {
if let Some(ref data) = self.data {
req.set_data_container(data.clone());
}
Either::A(srv.call(req))
} else if let Some(ref mut default) = self.default {
Either::A(default.call(req))
Expand Down Expand Up @@ -953,4 +1004,22 @@ mod tests {
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);
}
}

0 comments on commit 45c0597

Please sign in to comment.