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
#[macro_use]
extern crate lazy_static;
extern crate http;
extern crate inflector;
extern crate path_tree;

mod resource;

use http::Method;
use inflector::string::pluralize::to_plural;
use inflector::string::singularize::to_singular;
use path_tree::PathTree;
use std::collections::HashMap;

pub use resource::{Resource, ResourceOptions, Resources};

pub type Trees<H> = HashMap<Method, PathTree<H>>;

#[derive(Clone, Debug)]
pub struct Router<H> {
    path: String,
    trees: Trees<H>,
    middleware: Vec<H>,
}

impl<H> Router<H>
where
    H: Clone,
{
    pub fn new() -> Self {
        Router {
            trees: Trees::new(),
            path: "/".to_owned(),
            middleware: Vec::new(),
        }
    }

    // middleware
    pub fn middleware(&mut self, handler: H) -> &mut Self {
        self.middleware.push(handler);
        self
    }

    // scope with prefix
    pub fn scope(&mut self, path: &str, builder: impl FnOnce(&mut Router<H>)) -> &mut Self {
        let mut group = Router {
            trees: self.trees.clone(),
            path: join_paths(&self.path, path),
            middleware: self.middleware.clone(),
        };
        builder(&mut group);
        self.trees = group.trees;

        // let parent_path = self.path.to_owned();
        // self.path = join_paths(&self.path, path);
        // build(self);
        // self.path = parent_path;

        self
    }

    fn _handle(&mut self, method: Method, path: &str, handler: H) -> &mut Self {
        // TODO: combine middleware + handler to finally handler
        self.trees
            .entry(method)
            .or_insert_with(PathTree::new)
            .insert(path, handler);
        self
    }

    pub fn handle(&mut self, method: Method, path: &str, handler: H) -> &mut Self {
        self._handle(method, &join_paths(&self.path, path), handler)
    }

    pub fn get(&mut self, path: &str, handler: H) -> &mut Self {
        self.handle(Method::GET, path, handler)
    }

    pub fn post(&mut self, path: &str, handler: H) -> &mut Self {
        self.handle(Method::POST, path, handler)
    }

    pub fn delete(&mut self, path: &str, handler: H) -> &mut Self {
        self.handle(Method::DELETE, path, handler)
    }

    pub fn patch(&mut self, path: &str, handler: H) -> &mut Self {
        self.handle(Method::PATCH, path, handler)
    }

    pub fn put(&mut self, path: &str, handler: H) -> &mut Self {
        self.handle(Method::PUT, path, handler)
    }

    pub fn options(&mut self, path: &str, handler: H) -> &mut Self {
        self.handle(Method::OPTIONS, path, handler)
    }

    pub fn head(&mut self, path: &str, handler: H) -> &mut Self {
        self.handle(Method::HEAD, path, handler)
    }

    pub fn connect(&mut self, path: &str, handler: H) -> &mut Self {
        self.handle(Method::CONNECT, path, handler)
    }

    pub fn trace(&mut self, path: &str, handler: H) -> &mut Self {
        self.handle(Method::TRACE, path, handler)
    }

    pub fn any(&mut self, path: &str, handler: H) -> &mut Self {
        let path = &join_paths(&self.path, path);
        self._handle(Method::GET, path, handler.to_owned())
            ._handle(Method::POST, path, handler.to_owned())
            ._handle(Method::DELETE, path, handler.to_owned())
            ._handle(Method::PATCH, path, handler.to_owned())
            ._handle(Method::PUT, path, handler.to_owned())
            ._handle(Method::OPTIONS, path, handler.to_owned())
            ._handle(Method::HEAD, path, handler.to_owned())
            ._handle(Method::CONNECT, path, handler.to_owned())
            ._handle(Method::TRACE, path, handler.to_owned())
    }

    pub fn resource(&mut self, path: &str, resource: Vec<((&str, &str, &Method), H)>) -> &mut Self {
        let path = &join_paths(&self.path, &to_singular(path));
        for (r, m) in resource.iter() {
            let new_path = &join_paths(&path, r.1);
            self._handle(r.2.to_owned(), new_path, m.to_owned());
        }
        self
    }

    pub fn resources(
        &mut self,
        path: &str,
        resources: Vec<((&str, &str, &Method), H)>,
    ) -> &mut Self {
        let path = &join_paths(&self.path, &to_plural(path));
        for (r, m) in resources.iter() {
            let new_path = &join_paths(&path, &r.1.replace("id", &(to_singular(path) + "_id")));
            self._handle(r.2.to_owned(), new_path, m.to_owned());
        }
        self
    }

    pub fn find<'a>(
        &'a self,
        method: &'a Method,
        path: &'a str,
    ) -> Option<(&'a H, Vec<(&'a str, &'a str)>)> {
        let tree = self.trees.get(method)?;
        tree.find(path)
    }
}

fn join_paths(a: &str, mut b: &str) -> String {
    if b.is_empty() {
        return a.to_owned();
    }
    b = b.trim_start_matches('/');
    a.trim_end_matches('/').to_owned() + "/" + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_router() {
        type F = fn() -> usize;
        let mut router = Router::<F>::new();

        router
            // scope v1
            .scope("/v1", |v1| {
                v1.get("/login", || 0)
                    .post("/submit", || 1)
                    .delete("/read", || 2);
            })
            // scope v2
            .scope("/v2", |v2| {
                v2.get("/login", || 0)
                    .post("/submit", || 1)
                    .delete("/read", || 2);
            })
            .get("/foo", || 3)
            .post("/bar", || 4)
            .delete("/baz", || 5)
            // scope admin
            .scope("admin", |a| {
                a.any("/", || 6);
                // a.resources(
                //     "users",
                //     Resource {
                //         index: || 7,
                //         new: || 8,
                //     },
                // );
            });

        dbg!(&router);

        let r = router.find(&Method::DELETE, "/v1/read");
        assert!(r.is_some());
        let (h, p) = r.unwrap();
        assert_eq!(h(), 2);
        assert_eq!(p, []);

        let r = router.find(&Method::POST, "/v2/submit");
        assert!(r.is_some());
        let (h, p) = r.unwrap();
        assert_eq!(h(), 1);
        assert_eq!(p, []);

        let r = router.find(&Method::GET, "/foo");
        assert!(r.is_some());
        let (h, p) = r.unwrap();
        assert_eq!(h(), 3);
        assert_eq!(p, []);

        let r = router.find(&Method::POST, "/bar");
        assert!(r.is_some());
        let (h, p) = r.unwrap();
        assert_eq!(h(), 4);
        assert_eq!(p, []);

        let r = router.find(&Method::DELETE, "/baz");
        assert!(r.is_some());
        let (h, p) = r.unwrap();
        assert_eq!(h(), 5);
        assert_eq!(p, []);

        let r = router.find(&Method::HEAD, "/admin/");
        assert!(r.is_some());
        let (h, p) = r.unwrap();
        assert_eq!(h(), 6);
        assert_eq!(p, []);

        let r = router.find(&Method::OPTIONS, "/admin");
        assert!(r.is_none());

        // let r = router.find(&Method::GET, "/admin/users");
        // assert!(r.is_some());
        // let (h, p) = r.unwrap();
        // assert_eq!(h(), 7);
        // assert_eq!(p, []);

        // let r = router.find(&Method::GET, "/admin/users/new");
        // assert!(r.is_some());
        // let (h, p) = r.unwrap();
        // assert_eq!(h(), 8);
        // assert_eq!(p, []);
    }
}