1use crate::assets::PostAsset;
2use regex::Regex;
3
4const ACTION_REGEX: &str = r"/{0,1}(?P<action>\w*)/{0,1}(?P<id>.*)";
5
6pub enum Router {
7 NotFound,
8 Index,
9 Projects,
10 Post { page: String },
11}
12
13pub fn blog_post_exists(name: &str) -> bool {
14 PostAsset::iter().any(|x| name.eq(&x.to_string()))
15}
16
17impl Router {
18 pub fn new(path: &str) -> Router {
19 let re = Regex::new(ACTION_REGEX).unwrap();
20 let caps = re.captures(path);
21 let mut action = match caps {
22 Some(ref value) => &value["action"],
23 None => "index",
24 };
25
26 if action == "" {
27 action = "index"
28 }
29
30 // this 7 means the "/posts/" from the full path
31 let trimmed_path: String = path.chars().skip(7).collect();
32 if action.eq("posts") && !blog_post_exists(&trimmed_path) {
33 return Router::NotFound;
34 }
35
36 match action {
37 "posts" => Router::Post {
38 page: caps.unwrap()["id"].to_string(),
39 },
40 "projects" => Router::Projects,
41 "index" => Router::Index,
42 _ => Router::NotFound,
43 }
44 }
45}