album/src/photosdirmiddleware.rs

42 lines
993 B
Rust
Raw Normal View History

use nickel::{Continue, Middleware, MiddlewareResult, Request, Response};
use photosdir::PhotosDir;
2017-02-04 21:12:13 +04:00
use plugin::Extensible;
use std::path::PathBuf;
2017-02-04 21:12:13 +04:00
use typemap::Key;
pub struct PhotosDirMiddleware {
dir: PathBuf,
}
impl PhotosDirMiddleware {
2016-05-04 14:16:20 +03:00
pub fn new(dir: PathBuf) -> Self {
PhotosDirMiddleware { dir }
}
}
2016-05-04 14:16:20 +03:00
impl Key for PhotosDirMiddleware {
type Value = PhotosDir;
}
impl<D> Middleware<D> for PhotosDirMiddleware {
fn invoke<'mw, 'conn>(
&self,
req: &mut Request<'mw, 'conn, D>,
res: Response<'mw, D>,
) -> MiddlewareResult<'mw, D> {
2016-05-04 14:16:20 +03:00
req.extensions_mut()
2017-02-04 21:12:13 +04:00
.insert::<PhotosDirMiddleware>(PhotosDir::new(self.dir.clone()));
Ok(Continue(res))
}
}
pub trait PhotosDirRequestExtensions {
fn photos(&self) -> &PhotosDir;
}
impl<'a, 'b, D> PhotosDirRequestExtensions for Request<'a, 'b, D> {
fn photos(&self) -> &PhotosDir {
2018-07-06 01:28:57 +04:00
self.extensions().get::<PhotosDirMiddleware>().unwrap()
}
}