aboutsummaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: f89a39f8be5ce7ab57ac5866f12025003a2a3f0c (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
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
#![feature(plugin)]
#![plugin(rocket_codegen)]

extern crate diesel;
extern crate rocket;
extern crate rocket_blog;
extern crate rocket_contrib;
#[macro_use] extern crate bart_derive;
#[macro_use] extern crate serde_derive;

use self::diesel::prelude::*;
use self::rocket_blog::{schema, models};
use rocket_contrib::Json;
use rocket::response::{Response, Responder};
use rocket::request::Request;
use rocket::http::{ContentType, Status};
use std::io::Cursor;

mod posts;

#[derive(BartDisplay, Serialize)]
#[template = "templates/index.html"]
struct IndexTemplate<'a> {
    title: &'a str,
    posts: Vec<models::Post>
}

macro_rules! implement_responder_for {
    // Implement a responder for the given template type
    //
    // Seems I can't add the lifetime after the matcher,
    // like this: `$template_type<'a>`
    // So it will have to be passed in to the argument at
    // the macro incovation instead.
    ($template_type:ty) => (
        impl<'a> Responder<'a> for $template_type {
            fn respond_to(self, _: &Request) -> Result<Response<'static>, Status> {
                Response::build()
                    .header(ContentType::HTML)
                    .sized_body(Cursor::new(format!("{}", &self)))
                    .ok()
            }
        }
    )
}

implement_responder_for!(IndexTemplate<'a>);
implement_responder_for!(posts::NewPostTemplate<'a>);

fn get_posts(conn: rocket_blog::DbConn) -> Vec<models::Post> {
    use schema::posts::dsl::*;
    posts.filter(published.eq(false))
        .limit(5)
        .load::<models::Post>(&*conn)
        .expect("Error loading posts")
}

#[get("/", format = "text/html")]
fn index<'a>(conn: rocket_blog::DbConn) -> IndexTemplate<'a> {
    IndexTemplate { title: "Bloggen", posts: get_posts(conn) }
}

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

fn main() {
    rocket::ignite()
        .manage(rocket_blog::init_db_pool())
        .mount("/", routes![index, index_json])
        .mount("/posts", routes![posts::new, posts::create])
        .launch();
}