use {Rocket, Request, Response, Data};
use fairing::{Fairing, Kind, Info};
pub enum AdHoc {
#[doc(hidden)]
Attach(Box<Fn(Rocket) -> Result<Rocket, Rocket> + Send + Sync + 'static>),
#[doc(hidden)]
Launch(Box<Fn(&Rocket) + Send + Sync + 'static>),
#[doc(hidden)]
Request(Box<Fn(&mut Request, &Data) + Send + Sync + 'static>),
#[doc(hidden)]
Response(Box<Fn(&Request, &mut Response) + Send + Sync + 'static>),
}
impl AdHoc {
pub fn on_attach<F>(f: F) -> AdHoc
where F: Fn(Rocket) -> Result<Rocket, Rocket> + Send + Sync + 'static
{
AdHoc::Attach(Box::new(f))
}
pub fn on_launch<F>(f: F) -> AdHoc
where F: Fn(&Rocket) + Send + Sync + 'static
{
AdHoc::Launch(Box::new(f))
}
pub fn on_request<F>(f: F) -> AdHoc
where F: Fn(&mut Request, &Data) + Send + Sync + 'static
{
AdHoc::Request(Box::new(f))
}
pub fn on_response<F>(f: F) -> AdHoc
where F: Fn(&Request, &mut Response) + Send + Sync + 'static
{
AdHoc::Response(Box::new(f))
}
}
impl Fairing for AdHoc {
fn info(&self) -> Info {
use self::AdHoc::*;
match *self {
Attach(_) => {
Info {
name: "AdHoc::Attach",
kind: Kind::Attach,
}
}
Launch(_) => {
Info {
name: "AdHoc::Launch",
kind: Kind::Launch,
}
}
Request(_) => {
Info {
name: "AdHoc::Request",
kind: Kind::Request,
}
}
Response(_) => {
Info {
name: "AdHoc::Response",
kind: Kind::Response,
}
}
}
}
fn on_attach(&self, rocket: Rocket) -> Result<Rocket, Rocket> {
match *self {
AdHoc::Attach(ref callback) => callback(rocket),
_ => Ok(rocket),
}
}
fn on_launch(&self, rocket: &Rocket) {
if let AdHoc::Launch(ref callback) = *self {
callback(rocket)
}
}
fn on_request(&self, request: &mut Request, data: &Data) {
if let AdHoc::Request(ref callback) = *self {
callback(request, data)
}
}
fn on_response(&self, request: &Request, response: &mut Response) {
if let AdHoc::Response(ref callback) = *self {
callback(request, response)
}
}
}