Skip to content

Commit

Permalink
add App::register_data()
Browse files Browse the repository at this point in the history
  • Loading branch information
fafhrd91 committed Jun 5, 2019
1 parent a548b69 commit d9a62c4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
7 changes: 7 additions & 0 deletions src/app.rs
Expand Up @@ -100,6 +100,13 @@ where
self
}

/// Set application data. Application data could be accessed
/// by using `Data<T>` extractor where `T` is data type.
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
self.data.push(Box::new(data));
self
}

/// Run external configuration as part of the application building
/// process
///
Expand Down
23 changes: 22 additions & 1 deletion src/data.rs
Expand Up @@ -54,7 +54,7 @@ pub(crate) trait DataFactory {
///
/// let app = App::new()
/// // Store `MyData` in application storage.
/// .data(data.clone())
/// .register_data(data.clone())
/// .service(
/// web::resource("/index.html").route(
/// web::get().to(index)));
Expand Down Expand Up @@ -130,6 +130,7 @@ impl<T: 'static> DataFactory for Data<T> {
mod tests {
use actix_service::Service;

use super::*;
use crate::http::StatusCode;
use crate::test::{block_on, init_service, TestRequest};
use crate::{web, App, HttpResponse};
Expand All @@ -154,6 +155,26 @@ mod tests {
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}

#[test]
fn test_register_data_extractor() {
let mut srv =
init_service(App::new().register_data(Data::new(10usize)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
));

let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);

let mut srv =
init_service(App::new().register_data(Data::new(10u32)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
));
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}

#[test]
fn test_route_data_extractor() {
let mut srv =
Expand Down
2 changes: 1 addition & 1 deletion test-server/Cargo.toml
Expand Up @@ -32,7 +32,7 @@ ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
[dependencies]
actix-codec = "0.1.2"
actix-rt = "0.2.2"
actix-service = "0.4.1"
actix-service = "0.4.0"
actix-server = "0.5.1"
actix-utils = "0.4.1"
awc = "0.2.1"
Expand Down

0 comments on commit d9a62c4

Please sign in to comment.