From d9a62c4bbf9091a39aa5df05ae08a6a0a8e149ae Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Wed, 5 Jun 2019 08:43:39 +0600 Subject: [PATCH] add App::register_data() --- src/app.rs | 7 +++++++ src/data.rs | 23 ++++++++++++++++++++++- test-server/Cargo.toml | 2 +- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/app.rs b/src/app.rs index 1568d5fca..4f8b283e1 100644 --- a/src/app.rs +++ b/src/app.rs @@ -100,6 +100,13 @@ where self } + /// Set application data. Application data could be accessed + /// by using `Data` extractor where `T` is data type. + pub fn register_data(mut self, data: Data) -> Self { + self.data.push(Box::new(data)); + self + } + /// Run external configuration as part of the application building /// process /// diff --git a/src/data.rs b/src/data.rs index 1328c4ef6..9fd8b67fc 100644 --- a/src/data.rs +++ b/src/data.rs @@ -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))); @@ -130,6 +130,7 @@ impl DataFactory for Data { 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}; @@ -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| 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| 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 = diff --git a/test-server/Cargo.toml b/test-server/Cargo.toml index 37e2b0444..a8f4425ba 100644 --- a/test-server/Cargo.toml +++ b/test-server/Cargo.toml @@ -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"