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
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
use std::{collections::HashMap, fmt, sync::Arc};

use viz_core::{
    http, Context, DynMiddleware, Endpoint, Extract, Future, Handler, Middleware, Response, Result,
    VecMiddleware,
};

use crate::Method;

macro_rules! verbs {
    ($(($name:ident, $verb:ident),)*) => {
        $(
            #[doc = concat!(" Appends a route, handle HTTP verb `", stringify!($verb), "`")]
            pub fn $name<H, A>(self, h: H) -> Self
            where
                A: Extract,
                A::Error: Into<Response>,
                H: Handler<A>,
                H::Output: Into<Response>,
                H::Future: Future<Output = H::Output> + Send + 'static,
                Endpoint<H, A>: for<'m> Middleware<'m, Context, Output = Result>,
            {
                self.on(Method::Verb(http::Method::$verb), h)
            }
        )*
    }
}

macro_rules! stand_alone_verbs {
    ($(($name:ident, $verb:ident),)*) => {
        $(
            #[doc = concat!(" Appends a route, handle HTTP verb `", stringify!($verb), "`")]
            pub fn $name<H, A>(h: H) -> Route
            where
                A: Extract,
                A::Error: Into<Response>,
                H: Handler<A>,
                H::Output: Into<Response>,
                H::Future: Future<Output = H::Output> + Send + 'static,
                Endpoint<H, A>: for<'m> Middleware<'m, Context, Output = Result>,
            {

                Route::on(Route::new(""), Method::Verb(http::Method::$verb), h)
            }
        )*
    }
}

/// Route
pub struct Route {
    // inherit parrent's middleware
    pub(crate) inherit: bool,
    pub(crate) path: String,
    pub(crate) name: Option<String>,
    pub(crate) middleware: Option<VecMiddleware>,
    pub(crate) handlers: HashMap<Method, Arc<DynMiddleware>>,
}

impl Route {
    /// Creates new Route Instance
    pub fn new(path: &str) -> Self {
        Self {
            handlers: HashMap::new(),
            path: path.to_owned(),
            middleware: None,
            inherit: true,
            name: None,
        }
    }

    /// Sets a path
    pub fn path(mut self, path: &str) -> Self {
        self.path.insert_str(0, path);
        self
    }

    /// Sets a name
    pub fn name(mut self, name: &str) -> Self {
        self.name.replace(name.to_owned());
        self
    }

    /// Sets a inherit
    pub fn inherit(mut self, b: bool) -> Self {
        self.inherit = b;
        self
    }

    /// Appends a middleware
    pub fn with<M>(mut self, m: M) -> Self
    where
        M: for<'m> Middleware<'m, Context, Output = Result>,
    {
        self.middleware.get_or_insert_with(Vec::new).insert(0, Arc::new(m));
        self
    }

    /// Appends a route, handle HTTP verb
    pub fn on<H, A>(mut self, method: Method, h: H) -> Self
    where
        A: Extract,
        A::Error: Into<Response>,
        H: Handler<A>,
        H::Output: Into<Response>,
        H::Future: Future<Output = H::Output> + Send + 'static,
        Endpoint<H, A>: for<'m> Middleware<'m, Context, Output = Result>,
    {
        self.handlers.insert(method, Arc::new(Endpoint::new(h)));
        self
    }

    verbs! {
        (get, GET),
        (post, POST),
        (put, PUT),
        (delete, DELETE),
        (options, OPTIONS),
        (connect, CONNECT),
        (patch, PATCH),
        (trace, TRACE),
    }

    /// Appends a route, handle any HTTP verbs
    pub fn any<H, A>(self, h: H) -> Self
    where
        A: Extract,
        A::Error: Into<Response>,
        H: Handler<A>,
        H::Output: Into<Response>,
        H::Future: Future<Output = H::Output> + Send + 'static,
        Endpoint<H, A>: for<'m> Middleware<'m, Context, Output = Result>,
    {
        self.on(Method::Any, h)
    }

    /// Appends a route, only handle HTTP verbs
    pub fn only<H, A, const S: usize>(mut self, methods: [Method; S], h: H) -> Self
    where
        A: Extract,
        A::Error: Into<Response>,
        H: Handler<A>,
        H::Output: Into<Response>,
        H::Future: Future<Output = H::Output> + Send + 'static,
        Endpoint<H, A>: for<'m> Middleware<'m, Context, Output = Result>,
    {
        methods.iter().cloned().for_each(|method| {
            self.handlers.insert(method, Arc::new(Endpoint::new(h.clone())));
        });
        self
    }

    /// Appends a route, except handle verbs
    pub fn except<H, A, const S: usize>(mut self, methods: [Method; S], h: H) -> Self
    where
        A: Extract,
        A::Error: Into<Response>,
        H: Handler<A>,
        H::Output: Into<Response>,
        H::Future: Future<Output = H::Output> + Send + 'static,
        Endpoint<H, A>: for<'m> Middleware<'m, Context, Output = Result>,
    {
        let mut verbs = vec![
            Method::Verb(http::Method::GET),
            Method::Verb(http::Method::POST),
            Method::Verb(http::Method::PUT),
            Method::Verb(http::Method::DELETE),
            Method::Verb(http::Method::OPTIONS),
            Method::Verb(http::Method::CONNECT),
            Method::Verb(http::Method::PATCH),
            Method::Verb(http::Method::TRACE),
        ];

        verbs.dedup_by_key(|m| methods.contains(m));

        verbs.iter().cloned().for_each(|method| {
            self.handlers.insert(method, Arc::new(Endpoint::new(h.clone())));
        });

        self
    }
}

impl fmt::Debug for Route {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.handlers
            .keys()
            .fold(
                f.debug_struct("Route")
                    .field("path", &self.path)
                    .field("name", &self.name.as_ref().map_or_else(String::new, |v| v.to_owned()))
                    .field("inherit", &self.inherit)
                    .field("middle", &self.middleware.as_ref().map_or_else(|| 0, |v| v.len())),
                |acc, x| acc.field("verb", &x),
            )
            .finish()
    }
}

/// Creates new Route
pub fn route(path: &str) -> Route {
    Route::new(path)
}

/// Appends a middleware
pub fn with<M>(m: M) -> Route
where
    M: for<'m> Middleware<'m, Context, Output = Result>,
{
    Route::with(Route::new(""), m)
}

stand_alone_verbs! {
    (get, GET),
    (post, POST),
    (put, PUT),
    (delete, DELETE),
    (options, OPTIONS),
    (connect, CONNECT),
    (patch, PATCH),
    (trace, TRACE),
}

/// Appends a route, handle any HTTP verbs
pub fn any<H, A>(h: H) -> Route
where
    A: Extract,
    A::Error: Into<Response>,
    H: Handler<A>,
    H::Output: Into<Response>,
    H::Future: Future<Output = H::Output> + Send + 'static,
    Endpoint<H, A>: for<'m> Middleware<'m, Context, Output = Result>,
{
    Route::any(Route::new(""), h)
}

/// Appends a route, only handle HTTP verbs
pub fn only<H, A, const S: usize>(methods: [Method; S], h: H) -> Route
where
    A: Extract,
    A::Error: Into<Response>,
    H: Handler<A>,
    H::Output: Into<Response>,
    H::Future: Future<Output = H::Output> + Send + 'static,
    Endpoint<H, A>: for<'m> Middleware<'m, Context, Output = Result>,
{
    Route::only(Route::new(""), methods, h)
}

/// Appends a route, except handle verbs
pub fn except<H, A, const S: usize>(methods: [Method; S], h: H) -> Route
where
    A: Extract,
    A::Error: Into<Response>,
    H: Handler<A>,
    H::Output: Into<Response>,
    H::Future: Future<Output = H::Output> + Send + 'static,
    Endpoint<H, A>: for<'m> Middleware<'m, Context, Output = Result>,
{
    Route::except(Route::new(""), methods, h)
}