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