1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use crate::{
    http::{Body, Request, Response, StatusCode},
    Result,
};

macro_rules! blank_status_response {
    ($status:expr) => {
        Ok(Response::builder()
            .status($status)
            .body(Body::empty())
            .unwrap())
    };
}

/// Implement this trait to create a view.
///
/// A view is a collection of methods that are called when a request is made to a specific route.
///
/// The methods are called based on the HTTP method of the request. For example, if a request is made to a route with a `GET` method, the `get` method will be called.
///
/// If a method is not implemented, a `405 Method Not Allowed` response will be returned.
///
/// # Example
///
/// ```
/// # use swim_core::{Body, Request, Response, StatusCode, View, Result};
/// #[derive(Debug)]
/// pub struct HelloView;
///
/// #[async_trait::async_trait]
/// impl View for HelloView {
///     async fn get(&self, request: Request<Body>) -> Result<Response<Body>> {
///         Ok(Response::builder()
///             .status(StatusCode::OK)
///             .body(Body::from("Say hello to Swim!"))
///             .unwrap())
///     }
/// }
/// ```
#[allow(unused_variables)]
#[async_trait::async_trait]
pub trait View: std::fmt::Debug + Send + Sync + 'static {
    /// Called when a request is made to a route with a `GET` method.
    async fn get(&self, request: Request<Body>) -> Result<Response<Body>> {
        blank_status_response!(StatusCode::NOT_FOUND)
    }

    /// Called when a request is made to a route with a `POST` method.
    async fn post(&self, request: Request<Body>) -> Result<Response<Body>> {
        blank_status_response!(StatusCode::METHOD_NOT_ALLOWED)
    }

    /// Called when a request is made to a route with a `PUT` method.
    async fn put(&self, request: Request<Body>) -> Result<Response<Body>> {
        blank_status_response!(StatusCode::METHOD_NOT_ALLOWED)
    }

    /// Called when a request is made to a route with a `PATCH` method.
    async fn patch(&self, request: Request<Body>) -> Result<Response<Body>> {
        blank_status_response!(StatusCode::METHOD_NOT_ALLOWED)
    }

    /// Called when a request is made to a route with a `DELETE` method.
    async fn delete(&self, request: Request<Body>) -> Result<Response<Body>> {
        blank_status_response!(StatusCode::METHOD_NOT_ALLOWED)
    }
}