aboutsummaryrefslogtreecommitdiffstats
path: root/src/controllers/home_controller.rs
blob: 38db52a1a0089110ef7477c95e3940374fcfae64 (plain) (blame)
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
use ::{models, utils};
use rocket;
use rocket_contrib::Json;
use std::path::PathBuf;
use posts_controller::ShowPostTemplate;

#[derive(BartDisplay, Serialize)]
#[template = "templates/index.html"]
struct IndexTemplate {
    posts: Vec<ShowPostTemplate>
}

implement_responder_for!(IndexTemplate);

#[get("/", format = "text/html")]
fn index(flash: Option<rocket::request::FlashMessage>, conn: utils::DbConn) -> utils::Page<IndexTemplate> {
    utils::Page {
        title: String::from("Bloggen"),
        flash: flash,
        content: IndexTemplate {
            posts: models::Post::get_all(conn).into_iter()
                .map(|p| ShowPostTemplate { post: p })
                .collect()
        }
    }
}

#[get("/", format = "application/json")]
fn index_json(conn: utils::DbConn) -> Json<Vec<models::Post>> {
    Json(models::Post::get_all(conn))
}

//
// Serve files from the public directory if no routes matches.
//
#[get("/<file..>", rank = 99)]
fn public_file(file: PathBuf) -> Option<rocket::response::NamedFile> {
    rocket::response::NamedFile::open(PathBuf::from("public/").join(file)).ok()
}

pub fn routes() -> Vec<rocket::Route> {
    routes![
        index,
        index_json,
        public_file
    ]
}