aboutsummaryrefslogtreecommitdiffstats
path: root/src/controllers/posts_controller.rs
blob: f10f312063b54c403bbf3e783b35ac4e905de295 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use comrak::{markdown_to_html, ComrakOptions};
use rocket;
use rocket::request::Form;
use rocket::response::{Flash, Redirect};
use utils;

#[derive(BartDisplay)]
#[template = "templates/new_post.html"]
pub struct NewPostTemplate {
    post: ::models::NewPost
}

implement_responder_for!(NewPostTemplate);

#[get("/new", format = "text/html")]
fn new(_conn: utils::DbConn) -> utils::Page<NewPostTemplate> {
    utils::Page {
        title: String::from("New post"),
        flash: None,
        content: NewPostTemplate {
            post: Default::default()
        }
    }
}

#[post("/create", data="<post>")]
fn create(post: Form<::models::NewPost>, conn: utils::DbConn) -> Flash<Redirect> {
    ::models::Post::create(post.get(), conn);
    Flash::success(Redirect::to("/"), "Post successfully created!")
}

#[derive(BartDisplay, Serialize)]
#[template = "templates/show_post.html"]
pub struct ShowPostTemplate {
    pub post: ::models::Post
}

implement_responder_for!(ShowPostTemplate);

impl ShowPostTemplate {
    pub fn rendered_body(&self) -> String {
        markdown_to_html(&self.post.body, &ComrakOptions::default())
    }
}

#[get("/<id>", format = "text/html")]
fn show(id: i32, conn: utils::DbConn) -> utils::Page<ShowPostTemplate> {
    let p = ::models::Post::get(id, conn);
    utils::Page {
        title: p.title.clone(),
        flash: None,
        content: ShowPostTemplate {
            post: p
        },
    }
}

#[derive(BartDisplay)]
#[template = "templates/edit_post.html"]
pub struct EditPostTemplate {
    post: ::models::Post
}

implement_responder_for!(EditPostTemplate);

#[get("/<id>/edit", format = "text/html")]
fn edit(id: i32, conn: utils::DbConn) -> utils::Page<EditPostTemplate> {
    let p = ::models::Post::get(id, conn);
    utils::Page {
        title: String::from("Edit post"),
        flash: None,
        content: EditPostTemplate { post: p }
    }
}

#[post("/update", data="<post>")]
fn update(post: Form<::models::Post>, conn: utils::DbConn) -> Flash<Redirect> {
  ::models::Post::update(post.get(), conn);
  Flash::success(Redirect::to("/"), "Post updated successfully!")
}

#[get("/<id>/delete", format = "text/html")]
fn delete(id: i32, conn: utils::DbConn) -> Flash<Redirect> {
    ::models::Post::delete(id, conn);
    Flash::success(Redirect::to("/"), "Post deleted!")
}

pub fn routes() -> Vec<rocket::Route> {
    routes![
        new,
        create,
        show,
        edit,
        update,
        delete
    ]
}