#[cfg(test)]
mod tests;
use std::sync::Arc;
use crate::app::App;
use crate::application::Application;
use crate::core::New;
use crate::middleware::{Middleware, WithMiddleware};
use crate::request::Request;
use crate::response::Response;
use crate::router::{PathParams, Router};
use crate::server::ConnectionInfo;
#[derive(Clone)]
pub struct AppWithState<S> {
state: Arc<S>,
router: Router,
}
impl<S: Send + Sync + 'static> AppWithState<S> {
pub fn new(state: S) -> Self {
AppWithState {
state: Arc::new(state),
router: Router::new(),
}
}
pub fn state(&self) -> &S {
&self.state
}
pub fn get<F>(mut self, pattern: &str, handler: F) -> Self
where
F: Fn(&Request, &PathParams, &ConnectionInfo, &S) -> Response + Send + Sync + 'static,
{
let state = Arc::clone(&self.state);
self.router = self.router.get(pattern, move |req, params, conn| {
handler(req, params, conn, &state)
});
self
}
pub fn post<F>(mut self, pattern: &str, handler: F) -> Self
where
F: Fn(&Request, &PathParams, &ConnectionInfo, &S) -> Response + Send + Sync + 'static,
{
let state = Arc::clone(&self.state);
self.router = self.router.post(pattern, move |req, params, conn| {
handler(req, params, conn, &state)
});
self
}
pub fn put<F>(mut self, pattern: &str, handler: F) -> Self
where
F: Fn(&Request, &PathParams, &ConnectionInfo, &S) -> Response + Send + Sync + 'static,
{
let state = Arc::clone(&self.state);
self.router = self.router.put(pattern, move |req, params, conn| {
handler(req, params, conn, &state)
});
self
}
pub fn patch<F>(mut self, pattern: &str, handler: F) -> Self
where
F: Fn(&Request, &PathParams, &ConnectionInfo, &S) -> Response + Send + Sync + 'static,
{
let state = Arc::clone(&self.state);
self.router = self.router.patch(pattern, move |req, params, conn| {
handler(req, params, conn, &state)
});
self
}
pub fn delete<F>(mut self, pattern: &str, handler: F) -> Self
where
F: Fn(&Request, &PathParams, &ConnectionInfo, &S) -> Response + Send + Sync + 'static,
{
let state = Arc::clone(&self.state);
self.router = self.router.delete(pattern, move |req, params, conn| {
handler(req, params, conn, &state)
});
self
}
pub fn mcp(self, name: impl Into<String>, version: impl Into<String>) -> crate::mcp::McpServer {
crate::mcp::McpServer::new(name, version).wrap(self)
}
pub fn wrap<M: Middleware + 'static>(self, layer: M) -> WithMiddleware<AppWithState<S>> {
WithMiddleware::new(self).wrap(layer)
}
}
impl<S: Send + Sync + 'static> Application for AppWithState<S> {
fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
if let Some(response) = self.router.handle(request, connection) {
return Ok(response);
}
App::new().execute(request, connection)
}
}