Conclude example

This commit is contained in:
finga 2021-04-14 23:02:09 +02:00
parent 13aacc3b6b
commit 78ef2762e7
21 changed files with 1809 additions and 6 deletions

View file

@ -0,0 +1,70 @@
#![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();
}

View file

@ -0,0 +1,34 @@
use crate::schema::posts::{self, dsl::posts as table_posts};
use diesel::{QueryResult, RunQueryDsl, SqliteConnection};
use rocket::FromForm;
use serde::Serialize;
#[derive(Queryable, Serialize)]
pub struct Post {
pub id: i32,
pub author: String,
pub email: String,
pub title: String,
pub content: String,
}
impl Post {
pub fn get_all(conn: &SqliteConnection) -> QueryResult<Vec<Post>> {
posts::table.load::<Post>(conn)
}
}
#[derive(Insertable, FromForm)]
#[table_name = "posts"]
pub struct NewPost {
pub author: String,
pub email: String,
pub title: String,
pub content: String,
}
impl NewPost {
pub fn insert(&self, conn: &SqliteConnection) -> QueryResult<usize> {
diesel::insert_into(table_posts).values(self).execute(conn)
}
}

View file

@ -0,0 +1,9 @@
table! {
posts (id) {
id -> Integer,
author -> Text,
email -> Text,
title -> Text,
content -> Text,
}
}