use crate::contracts::support::Responsable;
use crate::http::{Request, Response};
use async_trait::async_trait;
#[async_trait]
pub trait Controller: Send + Sync {
async fn index(&self, _req: Request) -> Response {
Response::not_implemented().text("501 Not Implemented: index")
}
async fn create(&self, _req: Request) -> Response {
Response::not_implemented().text("501 Not Implemented: create")
}
async fn store(&self, _req: Request) -> Response {
Response::not_implemented().text("501 Not Implemented: store")
}
async fn show(&self, _req: Request) -> Response {
Response::not_implemented().text("501 Not Implemented: show")
}
async fn edit(&self, _req: Request) -> Response {
Response::not_implemented().text("501 Not Implemented: edit")
}
async fn update(&self, _req: Request) -> Response {
Response::not_implemented().text("501 Not Implemented: update")
}
async fn destroy(&self, _req: Request) -> Response {
Response::not_implemented().text("501 Not Implemented: destroy")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::HttpStatus;
struct DummyController;
#[async_trait]
impl Controller for DummyController {}
struct BlogController;
#[async_trait]
impl Controller for BlogController {
async fn index(&self, _req: Request) -> Response {
"Blog Index".to_response()
}
async fn store(&self, _req: Request) -> Response {
(HttpStatus::Created, format!("Post created: {}", 1)).to_response()
}
async fn show(&self, _req: Request) -> Response {
Response::ok().json(r#"{"id": 1}"#)
}
}
#[tokio::test]
async fn test_default_controller_methods() {
let controller = DummyController;
let req = Request {
method: crate::http::Method::GET,
path: "/test".to_string(),
headers: std::collections::HashMap::new(),
body: Vec::new(),
};
let res = controller.index(req).await;
assert_eq!(res.status, HttpStatus::NotImplemented);
assert_eq!(res.status.code(), 501);
}
#[tokio::test]
async fn test_controller_responsable_return_types() {
let controller = BlogController;
let dummy_req = || Request {
method: crate::http::Method::GET,
path: "/test".to_string(),
headers: std::collections::HashMap::new(),
body: Vec::new(),
};
let res_str = controller.index(dummy_req()).await;
assert_eq!(res_str.status, HttpStatus::Ok);
assert_eq!(res_str.status.code(), 200);
assert_eq!(String::from_utf8(res_str.body).unwrap(), "Blog Index");
let res_tuple = controller.store(dummy_req()).await;
assert_eq!(res_tuple.status, HttpStatus::Created);
assert_eq!(res_tuple.status.code(), 201);
assert_eq!(String::from_utf8(res_tuple.body).unwrap(), "Post created: 1");
let res_resp = controller.show(dummy_req()).await;
assert_eq!(res_resp.status, HttpStatus::Ok);
assert_eq!(res_resp.status.code(), 200);
assert_eq!(String::from_utf8(res_resp.body).unwrap(), r#"{"id": 1}"#);
}
}