by_loco/controller/middleware/
compression.rs

1//! Compression Middleware for Axum
2//!
3//! This middleware applies compression to HTTP responses to reduce the size of
4//! the data being transmitted. This can improve performance by decreasing load
5//! times and reducing bandwidth usage. The middleware configuration allows for
6//! enabling or disabling compression based on the application settings.
7
8use axum::Router as AXRouter;
9use serde::{Deserialize, Serialize};
10use tower_http::compression::CompressionLayer;
11
12use crate::{app::AppContext, controller::middleware::MiddlewareLayer, Result};
13
14#[derive(Debug, Clone, Deserialize, Serialize)]
15pub struct Compression {
16    #[serde(default)]
17    pub enable: bool,
18}
19
20impl MiddlewareLayer for Compression {
21    /// Returns the name of the middleware
22    fn name(&self) -> &'static str {
23        "compression"
24    }
25
26    /// Returns whether the middleware is enabled or not
27    fn is_enabled(&self) -> bool {
28        self.enable
29    }
30
31    fn config(&self) -> serde_json::Result<serde_json::Value> {
32        serde_json::to_value(self)
33    }
34
35    /// Applies the Compression middleware layer to the Axum router.
36    fn apply(&self, app: AXRouter<AppContext>) -> Result<AXRouter<AppContext>> {
37        Ok(app.layer(CompressionLayer::new()))
38    }
39}