1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-01-31 02:52:53 +01:00

add App::register_data()

This commit is contained in:
Nikolay Kim 2019-06-05 08:43:39 +06:00
parent a548b69679
commit d9a62c4bbf
3 changed files with 30 additions and 2 deletions

View File

@ -100,6 +100,13 @@ where
self 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 /// Run external configuration as part of the application building
/// process /// process
/// ///

View File

@ -54,7 +54,7 @@ pub(crate) trait DataFactory {
/// ///
/// let app = App::new() /// let app = App::new()
/// // Store `MyData` in application storage. /// // Store `MyData` in application storage.
/// .data(data.clone()) /// .register_data(data.clone())
/// .service( /// .service(
/// web::resource("/index.html").route( /// web::resource("/index.html").route(
/// web::get().to(index))); /// web::get().to(index)));
@ -130,6 +130,7 @@ impl<T: 'static> DataFactory for Data<T> {
mod tests { mod tests {
use actix_service::Service; use actix_service::Service;
use super::*;
use crate::http::StatusCode; use crate::http::StatusCode;
use crate::test::{block_on, init_service, TestRequest}; use crate::test::{block_on, init_service, TestRequest};
use crate::{web, App, HttpResponse}; use crate::{web, App, HttpResponse};
@ -154,6 +155,26 @@ mod tests {
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); 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] #[test]
fn test_route_data_extractor() { fn test_route_data_extractor() {
let mut srv = let mut srv =

View File

@ -32,7 +32,7 @@ ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
[dependencies] [dependencies]
actix-codec = "0.1.2" actix-codec = "0.1.2"
actix-rt = "0.2.2" actix-rt = "0.2.2"
actix-service = "0.4.1" actix-service = "0.4.0"
actix-server = "0.5.1" actix-server = "0.5.1"
actix-utils = "0.4.1" actix-utils = "0.4.1"
awc = "0.2.1" awc = "0.2.1"