publish post
This commit is contained in:
parent
1be2f385b1
commit
13064b2cbd
|
@ -1,5 +1,5 @@
|
|||
use diesel::SqliteConnection;
|
||||
use diesel_demo::models::PostDraft;
|
||||
use diesel_demo::models::{Post, PostDraft};
|
||||
use libpt::log::{self, debug, error, trace};
|
||||
|
||||
use diesel_demo as lib;
|
||||
|
@ -33,10 +33,23 @@ fn repl(conn: &mut SqliteConnection) -> anyhow::Result<()> {
|
|||
help - show this menu\n\
|
||||
exit - exit the application\n\
|
||||
list - list all posts\n\
|
||||
publish [id] - delete the post with the id [id]\n\
|
||||
delete [id] - delete the post with the id [id]\n\
|
||||
new - create a new post"
|
||||
)
|
||||
} else if buf.starts_with("EXIT") {
|
||||
break;
|
||||
} else if buf.starts_with("PUBLISH") {
|
||||
let id: i32 = match get_id(&buf) {
|
||||
Some(i) => i,
|
||||
None => continue,
|
||||
};
|
||||
Post::publish(conn, id)?;
|
||||
} else if buf.starts_with("DELETE") {
|
||||
let id: i32 = match get_id(&buf) {
|
||||
Some(i) => i,
|
||||
None => continue,
|
||||
};
|
||||
} else if buf.starts_with("LIST") {
|
||||
let posts = lib::load_all_posts(conn)?;
|
||||
trace!("loaded posts for display: {posts:#?}");
|
||||
|
@ -47,9 +60,29 @@ fn repl(conn: &mut SqliteConnection) -> anyhow::Result<()> {
|
|||
error!("Could not submit the post: {e:?}");
|
||||
});
|
||||
} else {
|
||||
println!("Bad input: try 'help'");
|
||||
usage()
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn usage() {
|
||||
println!("Bad input: try 'help'");
|
||||
}
|
||||
|
||||
fn get_id(buf: &str) -> Option<i32> {
|
||||
match buf.split(' ').nth(1) {
|
||||
Some(s) => match s.parse() {
|
||||
Ok(i) => Some(i),
|
||||
Err(e) => {
|
||||
error!("could not parse the id: {e:?}");
|
||||
None
|
||||
}
|
||||
},
|
||||
None => {
|
||||
usage();
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use std::io::{self, Read, Write};
|
||||
|
||||
use diesel::prelude::*;
|
||||
use libpt::log::trace;
|
||||
use libpt::log::{info, trace};
|
||||
|
||||
use crate::schema::posts;
|
||||
|
||||
|
@ -21,6 +21,19 @@ pub struct Post {
|
|||
pub published: bool,
|
||||
}
|
||||
|
||||
impl Post {
|
||||
pub fn publish(conn: &mut SqliteConnection, id: i32) -> anyhow::Result<()> {
|
||||
use crate::schema::posts::dsl::{posts, published};
|
||||
|
||||
let post = diesel::update(posts.find(id))
|
||||
.set(published.eq(true))
|
||||
.returning(Post::as_returning())
|
||||
.get_result(conn)?;
|
||||
info!("updated post {}", post.id);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Insertable, Debug)]
|
||||
#[diesel(table_name = crate::schema::posts)]
|
||||
#[diesel(check_for_backend(diesel::sqlite::Sqlite))] // optional but improves generated compiler errors
|
||||
|
|
Loading…
Reference in New Issue