tide-delay 0.0.1

Middleware for the Tide web framework that delays responses
Documentation
use async_std::future;
use std::time::{Duration, SystemTime};
use tide::{Middleware, Next, Request, Response};

#[derive(Clone, Debug)]
pub struct DelayMiddleware {
    expected_duration: Duration,
}

impl DelayMiddleware {
    pub fn new(expected_duration: Duration) -> Self {
        Self { expected_duration }
    }
}

#[tide::utils::async_trait]
impl<State: Clone + Send + Sync + 'static> Middleware<State> for DelayMiddleware {
    async fn handle(&self, req: Request<State>, next: Next<'_, State>) -> tide::Result {
        let time = SystemTime::now();

        let res: Response = next.run(req).await;

        if let Ok(elapsed_duration) = time.elapsed() {
            if let Some(remaining_duration) = self.expected_duration.checked_sub(elapsed_duration) {
                let _ = future::timeout(remaining_duration, future::pending::<()>()).await;
            }
        }

        Ok(res)
    }
}