71 lines
1.5 KiB
Rust
71 lines
1.5 KiB
Rust
#![feature(decl_macro)]
|
|
|
|
#[macro_use]
|
|
extern crate diesel;
|
|
|
|
use std::{collections::HashMap, net::SocketAddr};
|
|
|
|
use anyhow;
|
|
use diesel::SqliteConnection;
|
|
use rocket::{
|
|
get, post,
|
|
request::{FlashMessage, Form},
|
|
response::{Flash, Redirect},
|
|
routes, uri,
|
|
};
|
|
use rocket_contrib::{database, templates::Template};
|
|
use serde::Serialize;
|
|
|
|
mod models;
|
|
mod schema;
|
|
|
|
use models::{NewPost, Post};
|
|
|
|
#[database("sqlite")]
|
|
struct DbCon(SqliteConnection);
|
|
|
|
#[derive(Serialize)]
|
|
struct Posts {
|
|
posts: Vec<Post>,
|
|
}
|
|
|
|
#[get("/")]
|
|
fn index(conn: DbCon) -> anyhow::Result<Template> {
|
|
Ok(Template::render(
|
|
"index",
|
|
Posts {
|
|
posts: Post::get_all(&conn)?,
|
|
},
|
|
))
|
|
}
|
|
|
|
#[get("/create")]
|
|
fn create_form(flash: Option<FlashMessage>) -> Template {
|
|
let mut context = HashMap::new();
|
|
|
|
if let Some(ref msg) = flash {
|
|
context.insert("flash", msg.msg());
|
|
}
|
|
|
|
Template::render("create", &context)
|
|
}
|
|
|
|
#[post("/create", data = "<post>")]
|
|
fn create_post(conn: DbCon, post: Form<NewPost>) -> Result<Redirect, Flash<Redirect>> {
|
|
match post.insert(&conn) {
|
|
Ok(_) => Ok(Redirect::to(uri!(index))),
|
|
Err(e) => Err(Flash::error(
|
|
Redirect::to(uri!(create_form)),
|
|
"Could not create post.".to_string(),
|
|
)),
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
rocket::ignite()
|
|
.mount("/", routes![index, create_form, create_post])
|
|
.attach(DbCon::fairing())
|
|
.attach(Template::fairing())
|
|
.launch();
|
|
}
|