completed the logic to add new posts from the admin panel

pull/1/head
kirbylife 2019-12-18 03:20:00 -06:00
parent efc22e7eb4
commit 27cac09a08
4 changed files with 29 additions and 17 deletions

View File

@ -1,5 +1,6 @@
use crate::controllers::posts;
use crate::misc::get_context;
use crate::models::NewPost;
use rocket::http::{Cookie, Cookies};
use rocket::request::Form;
use rocket::response::Redirect;
@ -14,13 +15,6 @@ struct Login {
password: String,
}
#[derive(FromForm, Debug)]
struct Post {
pub title: String,
pub content: String,
pub published: bool,
}
#[get("/")]
fn index(mut cookies: Cookies<'_>) -> Result<Redirect, Template> {
let password = env::var("admin_pass").expect("admin_pass not setted");
@ -92,22 +86,21 @@ fn add_post(mut cookies: Cookies<'_>) -> Result<Template, Redirect> {
}
#[post("/add_post", data = "<post>")]
fn write_post(mut cookies: Cookies<'_>, post: Form<Post>) -> Result<Template, Redirect> {
fn write_post(mut cookies: Cookies<'_>, post: Form<NewPost>) -> Redirect {
let password = env::var("admin_pass").expect("admin_pass not setted");
match cookies.get_private("user") {
Some(cookie) => {
if cookie.value() == password {
let context = get_context();
println!("{:?}", post);
Ok(Template::render("admin/add_post", context))
match posts::add_post(&post) {
Ok(post) => Redirect::to(format!("/post/{}", post.id)),
Err(_) => Redirect::to("admin/add_post"),
}
} else {
Err(Redirect::to("/admin"))
Redirect::to("/admin")
}
}
None => Err(Redirect::to("/admin")),
None => Redirect::to("/admin"),
}
}

View File

@ -15,7 +15,7 @@ fn establish_connection() -> PgConnection {
pub mod posts {
use crate::controllers::*;
use crate::models::Post;
use crate::models::{NewPost, Post};
pub const MAX_POSTS_PER_PAGE: u64 = 20;
@ -48,4 +48,13 @@ pub mod posts {
post
}
pub fn add_post(new_post: &NewPost) -> Result<Post, Error> {
use crate::schema::posts;
let connection = establish_connection();
diesel::insert_into(posts::table)
.values(new_post)
.get_result(&connection)
}
}

View File

@ -1,6 +1,8 @@
use chrono::NaiveDateTime;
use serde::Serialize;
use super::schema::posts;
#[derive(Queryable, Serialize)]
pub struct Post {
pub id: i32,
@ -10,3 +12,11 @@ pub struct Post {
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
}
#[derive(FromForm, Insertable, Debug)]
#[table_name = "posts"]
pub struct NewPost {
pub title: String,
pub content: String,
pub published: bool,
}

View File

@ -30,7 +30,7 @@
<input id="title" name="title" type="text"/>
<label for="">Visible</label>
<input name="published" type="checkbox" value="true"/>
<textarea id="content"name="content"></textarea>
<textarea id="content" name="content"></textarea>
<button>Publicar</button>
</form>
</div>