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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
use viz_core::{
    BoxHandler, Handler, HandlerExt, IntoResponse, Next, Request, Response, Result, Transform,
};

use crate::{Resources, Route};

macro_rules! export_verb {
    ($name:ident $verb:ty) => {
        #[doc = concat!(" Adds a handler with a path and HTTP `", stringify!($verb), "` verb pair.")]
        #[must_use]
        pub fn $name<S, H, O>(self, path: S, handler: H) -> Self
        where
            S: AsRef<str>,
            H: Handler<Request, Output = Result<O>> + Clone,
            O: IntoResponse + Send + 'static,
        {
            self.route(path, Route::new().$name(handler))
        }
    };
}

/// A routes collection.
#[derive(Clone, Debug, Default)]
pub struct Router {
    pub(crate) routes: Option<Vec<(String, Route)>>,
}

impl Router {
    /// Creates an empty `Router`.
    #[must_use]
    pub const fn new() -> Self {
        Self { routes: None }
    }

    fn push<S>(routes: &mut Vec<(String, Route)>, path: S, route: Route)
    where
        S: AsRef<str>,
    {
        let path = path.as_ref();
        match routes
            .iter_mut()
            .find_map(|(p, r)| if p == path { Some(r) } else { None })
        {
            Some(r) => {
                *r = route.into_iter().fold(
                    // original route
                    r.clone().into_iter().collect(),
                    |or: Route, (method, handler)| or.on(method, handler),
                );
            }
            None => routes.push((path.to_string(), route)),
        }
    }

    /// Inserts a path-route pair into the router.
    #[must_use]
    pub fn route<S>(mut self, path: S, route: Route) -> Self
    where
        S: AsRef<str>,
    {
        Self::push(
            self.routes.get_or_insert_with(Vec::new),
            path.as_ref().trim_start_matches('/'),
            route,
        );
        self
    }

    /// Nested resources with a path.
    #[must_use]
    pub fn resources<S>(self, path: S, resource: Resources) -> Self
    where
        S: AsRef<str>,
    {
        let mut path = path.as_ref().to_string();
        if !path.ends_with('/') {
            path.push('/');
        }

        resource.into_iter().fold(self, |router, (mut sp, route)| {
            let is_empty = sp.is_empty();
            sp = path.clone() + &sp;
            if is_empty {
                sp = sp.trim_end_matches('/').to_string();
            }
            router.route(sp, route)
        })
    }

    /// Nested sub-router with a path.
    #[allow(clippy::similar_names)]
    #[must_use]
    pub fn nest<S>(self, path: S, router: Self) -> Self
    where
        S: AsRef<str>,
    {
        let mut path = path.as_ref().to_string();
        if !path.ends_with('/') {
            path.push('/');
        }

        match router.routes {
            Some(routes) => routes.into_iter().fold(self, |router, (mut sp, route)| {
                let is_empty = sp.is_empty();
                sp = path.clone() + &sp;
                if is_empty {
                    sp = sp.trim_end_matches('/').to_string();
                }
                router.route(sp, route)
            }),
            None => self,
        }
    }

    repeat!(
        export_verb
        get GET
        post POST
        put PUT
        delete DELETE
        head HEAD
        options OPTIONS
        connect CONNECT
        patch PATCH
        trace TRACE
    );

    /// Adds a handler with a path and any HTTP verbs."
    #[must_use]
    pub fn any<S, H, O>(self, path: S, handler: H) -> Self
    where
        S: AsRef<str>,
        H: Handler<Request, Output = Result<O>> + Clone,
        O: IntoResponse + Send + 'static,
    {
        self.route(path, Route::new().any(handler))
    }

    /// Takes a closure and creates an iterator which calls that closure on each handler.
    #[must_use]
    pub fn map_handler<F>(self, f: F) -> Self
    where
        F: Fn(BoxHandler<Request, Result<Response>>) -> BoxHandler<Request, Result<Response>>,
    {
        Self {
            routes: self.routes.map(|routes| {
                routes
                    .into_iter()
                    .map(|(path, route)| {
                        (
                            path,
                            route
                                .into_iter()
                                .map(|(method, handler)| (method, f(handler)))
                                .collect(),
                        )
                    })
                    .collect()
            }),
        }
    }

    /// Transforms the types to a middleware and adds it.
    #[must_use]
    pub fn with<T>(self, t: T) -> Self
    where
        T: Transform<BoxHandler>,
        T::Output: Handler<Request, Output = Result<Response>> + Clone,
    {
        self.map_handler(|handler| t.transform(handler).boxed())
    }

    /// Adds a middleware for the routes.
    #[must_use]
    pub fn with_handler<H>(self, f: H) -> Self
    where
        H: Handler<Next<Request, BoxHandler>, Output = Result<Response>> + Clone,
    {
        self.map_handler(|handler| handler.around(f.clone()).boxed())
    }
}

#[cfg(test)]
#[allow(clippy::unused_async)]
mod tests {
    use http_body_util::{BodyExt, Full};
    use std::sync::Arc;
    use viz_core::{
        async_trait,
        types::{Params, RouteInfo},
        Body, Error, Handler, HandlerExt, IntoResponse, Method, Next, Request, RequestExt,
        Response, ResponseExt, Result, StatusCode, Transform,
    };

    use crate::{any, get, Resources, Route, Router, Tree};

    #[derive(Clone)]
    struct Logger;

    impl Logger {
        const fn new() -> Self {
            Self
        }
    }

    impl<H: Clone> Transform<H> for Logger {
        type Output = LoggerHandler<H>;

        fn transform(&self, h: H) -> Self::Output {
            LoggerHandler(h)
        }
    }

    #[derive(Clone)]
    struct LoggerHandler<H>(H);

    #[async_trait]
    impl<H> Handler<Request> for LoggerHandler<H>
    where
        H: Handler<Request>,
    {
        type Output = H::Output;

        async fn call(&self, req: Request) -> Self::Output {
            self.0.call(req).await
        }
    }

    #[tokio::test]
    async fn router() -> anyhow::Result<()> {
        async fn index(_: Request) -> Result<Response> {
            Ok(Response::text("index"))
        }

        async fn all(_: Request) -> Result<Response> {
            Ok(Response::text("any"))
        }

        async fn not_found(_: Request) -> Result<impl IntoResponse> {
            Ok(StatusCode::NOT_FOUND)
        }

        async fn search(_: Request) -> Result<Response> {
            Ok(Response::text("search"))
        }

        async fn show(req: Request) -> Result<Response> {
            let ids: Vec<String> = req.params()?;
            let items = ids.into_iter().fold(String::new(), |mut s, id| {
                s.push(' ');
                s.push_str(&id);
                s
            });
            Ok(Response::text("show".to_string() + &items))
        }

        async fn create(_: Request) -> Result<Response> {
            Ok(Response::text("create"))
        }

        async fn update(req: Request) -> Result<Response> {
            let ids: Vec<String> = req.params()?;
            let items = ids.into_iter().fold(String::new(), |mut s, id| {
                s.push(' ');
                s.push_str(&id);
                s
            });
            Ok(Response::text("update".to_string() + &items))
        }

        async fn delete(req: Request) -> Result<Response> {
            let ids: Vec<String> = req.params()?;
            let items = ids.into_iter().fold(String::new(), |mut s, id| {
                s.push(' ');
                s.push_str(&id);
                s
            });
            Ok(Response::text("delete".to_string() + &items))
        }

        async fn middle<H>((req, h): Next<Request, H>) -> Result<Response>
        where
            H: Handler<Request, Output = Result<Response>>,
        {
            h.call(req).await
        }

        let users = Resources::default()
            .named("user")
            .index(index)
            .create(create.before(|r: Request| async { Ok(r) }).around(middle))
            .show(show)
            .update(update)
            .destroy(delete)
            .map_handler(|h| {
                h.and_then(|res: Response| async {
                    let (parts, body) = res.into_parts();

                    let mut buf = bytes::BytesMut::new();
                    buf.extend(b"users: ");
                    buf.extend(body.collect().await.map_err(Error::boxed)?.to_bytes());

                    Ok(Response::from_parts(parts, Full::from(buf.freeze()).into()))
                })
                .boxed()
            });

        let posts = Router::new().route("search", get(search)).resources(
            "",
            Resources::default()
                .named("post")
                .create(create)
                .show(show)
                .update(update)
                .destroy(delete)
                .map_handler(|h| {
                    h.and_then(|res: Response| async {
                        let (parts, body) = res.into_parts();

                        let mut buf = bytes::BytesMut::new();
                        buf.extend(b"posts: ");
                        buf.extend(body.collect().await.map_err(Error::boxed)?.to_bytes());

                        Ok(Response::from_parts(parts, Full::from(buf.freeze()).into()))
                    })
                    .boxed()
                }),
        );

        let router = Router::new()
            // .route("", get(index))
            .get("", index)
            .resources("users", users.clone())
            .nest("posts", posts.resources(":post_id/users", users))
            .route("search", any(all))
            .route("*", Route::new().any(not_found))
            .with(Logger::new());

        let tree: Tree = router.into();

        // GET /posts
        let (req, method, path) = client(Method::GET, "/posts");
        let node = tree.find(&method, &path);
        assert!(node.is_some());
        let (h, _) = node.unwrap();
        assert_eq!(
            h.call(req).await?.into_body().collect().await?.to_bytes(),
            ""
        );

        // POST /posts
        let (req, method, path) = client(Method::POST, "/posts");
        let node = tree.find(&method, &path);
        assert!(node.is_some());
        let (h, _) = node.unwrap();
        assert_eq!(
            h.call(req).await?.into_body().collect().await?.to_bytes(),
            "posts: create"
        );

        // GET /posts/foo
        let (mut req, method, path) = client(Method::GET, "/posts/foo");
        let node = tree.find(&method, &path);
        assert!(node.is_some());
        let (h, route) = node.unwrap();
        req.extensions_mut().insert(Arc::from(RouteInfo {
            id: *route.id,
            pattern: route.pattern(),
            params: route.params().into(),
        }));
        assert_eq!(
            h.call(req).await?.into_body().collect().await?.to_bytes(),
            "posts: show foo"
        );

        // PUT /posts/foo
        let (mut req, method, path) = client(Method::PUT, "/posts/foo");
        let node = tree.find(&method, &path);
        assert!(node.is_some());
        let (h, route) = node.unwrap();
        req.extensions_mut().insert(Arc::from(RouteInfo {
            id: *route.id,
            pattern: route.pattern(),
            params: Into::<Params>::into(route.params()),
        }));
        assert_eq!(
            h.call(req).await?.into_body().collect().await?.to_bytes(),
            "posts: update foo"
        );

        // DELETE /posts/foo
        let (mut req, method, path) = client(Method::DELETE, "/posts/foo");
        let node = tree.find(&method, &path);
        assert!(node.is_some());
        let (h, route) = node.unwrap();
        req.extensions_mut().insert(Arc::from(RouteInfo {
            id: *route.id,
            pattern: route.pattern(),
            params: route.params().into(),
        }));
        assert_eq!(
            h.call(req).await?.into_body().collect().await?.to_bytes(),
            "posts: delete foo"
        );

        // GET /posts/foo/users
        let (req, method, path) = client(Method::GET, "/posts/foo/users");
        let node = tree.find(&method, &path);
        assert!(node.is_some());
        let (h, _) = node.unwrap();
        assert_eq!(
            h.call(req).await?.into_body().collect().await?.to_bytes(),
            "users: index"
        );

        // POST /posts/users
        let (req, method, path) = client(Method::POST, "/posts/foo/users");
        let node = tree.find(&method, &path);
        assert!(node.is_some());
        let (h, _) = node.unwrap();
        assert_eq!(
            h.call(req).await?.into_body().collect().await?.to_bytes(),
            "users: create"
        );

        // GET /posts/foo/users/bar
        let (mut req, method, path) = client(Method::GET, "/posts/foo/users/bar");
        let node = tree.find(&method, &path);
        assert!(node.is_some());
        let (h, route) = node.unwrap();
        req.extensions_mut().insert(Arc::from(RouteInfo {
            id: *route.id,
            pattern: route.pattern(),
            params: route.params().into(),
        }));
        assert_eq!(
            h.call(req).await?.into_body().collect().await?.to_bytes(),
            "users: show foo bar"
        );

        // PUT /posts/foo/users/bar
        let (mut req, method, path) = client(Method::PUT, "/posts/foo/users/bar");
        let node = tree.find(&method, &path);
        assert!(node.is_some());
        let (h, route) = node.unwrap();
        let route_info = Arc::from(RouteInfo {
            id: *route.id,
            pattern: route.pattern(),
            params: route.params().into(),
        });
        assert_eq!(route.pattern(), "/posts/:post_id/users/:user_id");
        assert_eq!(route_info.pattern, "/posts/:post_id/users/:user_id");
        req.extensions_mut().insert(route_info);
        assert_eq!(
            h.call(req).await?.into_body().collect().await?.to_bytes(),
            "users: update foo bar"
        );

        // DELETE /posts/foo/users/bar
        let (mut req, method, path) = client(Method::DELETE, "/posts/foo/users/bar");
        let node = tree.find(&method, &path);
        assert!(node.is_some());
        let (h, route) = node.unwrap();
        req.extensions_mut().insert(Arc::from(RouteInfo {
            id: *route.id,
            pattern: route.pattern(),
            params: route.params().into(),
        }));
        assert_eq!(
            h.call(req).await?.into_body().collect().await?.to_bytes(),
            "users: delete foo bar"
        );

        Ok(())
    }

    #[test]
    fn debug() {
        let search = Route::new().get(|_: Request| async { Ok(Response::text("search")) });

        let orgs = Resources::default()
            .index(|_: Request| async { Ok(Response::text("list posts")) })
            .create(|_: Request| async { Ok(Response::text("create post")) })
            .show(|_: Request| async { Ok(Response::text("show post")) });

        let settings = Router::new()
            .get("/", |_: Request| async { Ok(Response::text("settings")) })
            .get("/:page", |_: Request| async {
                Ok(Response::text("setting page"))
            });

        let app = Router::new()
            .get("/", |_: Request| async { Ok(Response::text("index")) })
            .route("search", search.clone())
            .resources(":org", orgs)
            .nest("settings", settings)
            .nest("api", Router::new().route("/search", search));

        let tree: Tree = app.into();

        assert_eq!(
            format!("{tree:#?}"),
            "Tree {
    method: GET,
    paths: 
    / •0
    ├── api/search •6
    ├── se
    │   ├── arch •1
    │   └── ttings •4
    │       └── /
    │           └── : •5
    └── : •2
        └── /
            └── : •3
    ,
    method: POST,
    paths: 
    /
    └── : •0
    ,
}"
        );
    }

    fn client(method: Method, path: &str) -> (Request, Method, String) {
        (
            Request::builder()
                .method(method.clone())
                .uri(path.to_owned())
                .body(Body::Empty)
                .unwrap(),
            method,
            path.to_string(),
        )
    }
}