mirror of https://github.com/fafhrd91/actix-web
Adding app_data to ServiceConfig (#1757)
This commit is contained in:
parent
20078fe603
commit
9a26ee56fa
|
@ -61,6 +61,11 @@ impl Extensions {
|
|||
pub fn clear(&mut self) {
|
||||
self.map.clear();
|
||||
}
|
||||
|
||||
/// Extends it with the content for another `Extensions`
|
||||
pub fn extend(&mut self, extensions: Extensions) {
|
||||
self.map.extend(extensions.map);
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Extensions {
|
||||
|
|
|
@ -183,6 +183,7 @@ where
|
|||
self.data.extend(cfg.data);
|
||||
self.services.extend(cfg.services);
|
||||
self.external.extend(cfg.external);
|
||||
self.extensions.extend(cfg.extensions);
|
||||
self
|
||||
}
|
||||
|
||||
|
|
|
@ -178,6 +178,7 @@ pub struct ServiceConfig {
|
|||
pub(crate) services: Vec<Box<dyn AppServiceFactory>>,
|
||||
pub(crate) data: Vec<Box<dyn DataFactory>>,
|
||||
pub(crate) external: Vec<ResourceDef>,
|
||||
pub(crate) extensions: Extensions,
|
||||
}
|
||||
|
||||
impl ServiceConfig {
|
||||
|
@ -186,6 +187,7 @@ impl ServiceConfig {
|
|||
services: Vec::new(),
|
||||
data: Vec::new(),
|
||||
external: Vec::new(),
|
||||
extensions: Extensions::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -198,6 +200,17 @@ impl ServiceConfig {
|
|||
self
|
||||
}
|
||||
|
||||
/// Set application level arbitrary data item.
|
||||
///
|
||||
/// Application data stored with `App::app_data()` method is available
|
||||
/// via `HttpRequest::app_data()` method at runtime.
|
||||
///
|
||||
/// Note: this method is ignored for `Scope::configure` method
|
||||
pub fn app_data<U: 'static>(&mut self, ext: U) -> &mut Self {
|
||||
self.extensions.insert(ext);
|
||||
self
|
||||
}
|
||||
|
||||
/// Configure route for a specific path.
|
||||
///
|
||||
/// This is same as `App::route()` method.
|
||||
|
@ -254,11 +267,15 @@ mod tests {
|
|||
async fn test_data() {
|
||||
let cfg = |cfg: &mut ServiceConfig| {
|
||||
cfg.data(10usize);
|
||||
cfg.app_data(10usize);
|
||||
};
|
||||
|
||||
let mut srv =
|
||||
init_service(App::new().configure(cfg).service(
|
||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||
web::resource("/").to(|_: web::Data<usize>, req: HttpRequest| {
|
||||
assert_eq!(*req.app_data::<usize>().unwrap(), 10usize);
|
||||
HttpResponse::Ok()
|
||||
}),
|
||||
))
|
||||
.await;
|
||||
let req = TestRequest::default().to_request();
|
||||
|
|
Loading…
Reference in New Issue