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