aboutsummaryrefslogtreecommitdiff
path: root/src/router.rs
blob: c5efd9c982c675da05df8a583978ccbcb5bf140d (plain)
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
use crate::assets::PostAsset;
use regex::Regex;

const ACTION_REGEX: &str = r"/{0,1}(?P<action>\w*)/{0,1}(?P<id>.*)";

pub enum Router {
    NotFound,
    Index,
    Projects,
    Post { page: String },
}

pub fn blog_post_exists(name: &str) -> bool {
    PostAsset::iter().any(|x| name.eq(&x.to_string()))
}

impl Router {
    pub fn new(path: &str) -> Router {
        let re = Regex::new(ACTION_REGEX).unwrap();
        let caps = re.captures(path);
        let mut action = match caps {
            Some(ref value) => &value["action"],
            None => "index",
        };

        if action == "" {
            action = "index"
        }

        // this 7 means the "/posts/" from the full path
        let trimmed_path: String = path.chars().skip(7).collect();
        if action.eq("posts") && !blog_post_exists(&trimmed_path) {
            return Router::NotFound;
        }

        match action {
            "posts" => Router::Post {
                page: caps.unwrap()["id"].to_string(),
            },
            "projects" => Router::Projects,
            "index" => Router::Index,
            _ => Router::NotFound,
        }
    }
}