Added /blog/edit, inline documentation

This commit is contained in:
Leonard Lorenz 2020-10-26 12:17:52 +01:00
parent a90ca863e7
commit 6e72cba14c
4 changed files with 52 additions and 7 deletions

View file

@ -92,6 +92,6 @@ async fn blog_hide_post(
#[get("/api/blog/posts")] #[get("/api/blog/posts")]
async fn blog_get_posts_json() -> impl Responder { async fn blog_get_posts_json() -> impl Responder {
let posts = get_posts(); let posts = get_all_posts();
HttpResponse::Ok().json(posts) HttpResponse::Ok().json(posts)
} }

View file

@ -1,5 +1,8 @@
use std::string::String; use std::string::String;
/// gets a value from an environment variable and returns it.
/// if this call was mandatory and it couldn't get a value, it will exit
/// the program and write an error message.
pub fn get_from_env(variable: &str, mandatory: bool) -> String { pub fn get_from_env(variable: &str, mandatory: bool) -> String {
std::env::var(variable).unwrap_or_else(|_| { std::env::var(variable).unwrap_or_else(|_| {
if mandatory { if mandatory {

View file

@ -6,6 +6,7 @@ use diesel::prelude::*;
use diesel::sqlite::SqliteConnection; use diesel::sqlite::SqliteConnection;
use models::*; use models::*;
/// Returns an SqliteConnection if connection successful.
fn establish_connection() -> SqliteConnection { fn establish_connection() -> SqliteConnection {
let root_path = config::get_from_env("ROOT_PATH", true); let root_path = config::get_from_env("ROOT_PATH", true);
let db_path = root_path + "/db.sqlite3"; let db_path = root_path + "/db.sqlite3";
@ -13,7 +14,19 @@ fn establish_connection() -> SqliteConnection {
.unwrap_or_else(|_| panic!("Error, connection to {} failed.", &db_path)) .unwrap_or_else(|_| panic!("Error, connection to {} failed.", &db_path))
} }
pub fn get_posts() -> std::vec::Vec<Post> { /// Returns all posts
pub fn get_all_posts() -> std::vec::Vec<Post> {
use schema::posts::dsl::*;
let connection = establish_connection();
posts
.filter(published.eq(true))
.order(id.desc())
.load::<Post>(&connection)
.expect("Error, couldn't load posts.")
}
/// Returns the last five posts.
pub fn get_last_five_posts() -> std::vec::Vec<Post> {
use schema::posts::dsl::*; use schema::posts::dsl::*;
let connection = establish_connection(); let connection = establish_connection();
posts posts
@ -24,6 +37,7 @@ pub fn get_posts() -> std::vec::Vec<Post> {
.expect("Error, couldn't load posts.") .expect("Error, couldn't load posts.")
} }
/// Returns the post with the given ID.
pub fn get_post_by_id(post_id: i32) -> Post { pub fn get_post_by_id(post_id: i32) -> Post {
use schema::posts::dsl::*; use schema::posts::dsl::*;
let connection = establish_connection(); let connection = establish_connection();
@ -33,6 +47,7 @@ pub fn get_post_by_id(post_id: i32) -> Post {
.expect("Error, couldn't find post.") .expect("Error, couldn't find post.")
} }
/// Creates a post and publishes it.
pub fn create_post(title: &str, body: &str) { pub fn create_post(title: &str, body: &str) {
use chrono::prelude::*; use chrono::prelude::*;
use schema::posts; use schema::posts;
@ -52,6 +67,7 @@ pub fn create_post(title: &str, body: &str) {
.unwrap_or_else(|_| panic!("Error, couldn't insert new Post.")); .unwrap_or_else(|_| panic!("Error, couldn't insert new Post."));
} }
/// Updates a post with the new title and body.
pub fn edit_post_by_id(post_id: i32, new_title: &str, new_body: &str) { pub fn edit_post_by_id(post_id: i32, new_title: &str, new_body: &str) {
use schema::posts::dsl::*; use schema::posts::dsl::*;
let connection = establish_connection(); let connection = establish_connection();
@ -63,6 +79,7 @@ pub fn edit_post_by_id(post_id: i32, new_title: &str, new_body: &str) {
.expect("Error, couldn't update post."); .expect("Error, couldn't update post.");
} }
/// Deletes a post by id.
pub fn delete_post_by_id(post_id: i32) { pub fn delete_post_by_id(post_id: i32) {
use schema::posts::dsl::*; use schema::posts::dsl::*;
let connection = establish_connection(); let connection = establish_connection();
@ -72,6 +89,7 @@ pub fn delete_post_by_id(post_id: i32) {
.expect("Error, couldn't update post."); .expect("Error, couldn't update post.");
} }
/// Sets the published bool of a post to false.
pub fn hide_post_by_id(post_id: i32) { pub fn hide_post_by_id(post_id: i32) {
use schema::posts::dsl::*; use schema::posts::dsl::*;
let connection = establish_connection(); let connection = establish_connection();

View file

@ -1,10 +1,11 @@
use crate::config; use crate::config;
use crate::db::*; use crate::db;
use actix_files as fs; use actix_files as fs;
use actix_web::{get, http::StatusCode, web, HttpResponse, Responder}; use actix_web::{get, http::StatusCode, web, HttpResponse, Responder};
use tera::{Context, Tera}; use tera::{Context, Tera};
/// authorizes a request by comparing it to the SUBMIT_TOKEN environment variable
pub fn authorized(form_token: &str) -> bool { pub fn authorized(form_token: &str) -> bool {
let token = config::get_from_env("SUBMIT_TOKEN", true); let token = config::get_from_env("SUBMIT_TOKEN", true);
if token == form_token { if token == form_token {
@ -13,6 +14,10 @@ pub fn authorized(form_token: &str) -> bool {
false false
} }
/// tests if the post id is a valid i32 integer bigger than zero
/// assert(!(id_valid("2147483648").0))
/// assert(!(id_valid("-1").0))
/// assert(id_valid("1").0))
pub fn id_valid(post_id: String) -> (bool, i32) { pub fn id_valid(post_id: String) -> (bool, i32) {
match post_id.parse::<i32>() { match post_id.parse::<i32>() {
Err(_) => (false, 0), Err(_) => (false, 0),
@ -26,10 +31,14 @@ pub fn id_valid(post_id: String) -> (bool, i32) {
} }
} }
/// replaces the \n character with a <br> html tag
/// assert(replace_newlines("test\ntest") == "test<br>test")
pub fn replace_newlines(x: &str) -> String { pub fn replace_newlines(x: &str) -> String {
x.replace("\n", "<br>") x.replace("\n", "<br>")
} }
/// replaces the \n character with a <br> html tag
/// assert(replace_newlines("test<br>test") == "test\ntest")
pub fn replace_br_tags(x: &str) -> String { pub fn replace_br_tags(x: &str) -> String {
x.replace("<br>", "\n") x.replace("<br>", "\n")
} }
@ -44,7 +53,7 @@ async fn root() -> impl Responder {
async fn blog() -> impl Responder { async fn blog() -> impl Responder {
let root_path = config::get_from_env("ROOT_PATH", true); let root_path = config::get_from_env("ROOT_PATH", true);
let posts = get_posts(); let posts = db::get_last_five_posts();
let mut context = Context::new(); let mut context = Context::new();
context.insert("posts", &posts); context.insert("posts", &posts);
@ -87,7 +96,7 @@ async fn blog_by_id(web::Path(post_id): web::Path<std::string::String>) -> impl
if valid { if valid {
let root_path = config::get_from_env("ROOT_PATH", true); let root_path = config::get_from_env("ROOT_PATH", true);
let post = get_post_by_id(id as i32); let post = db::get_post_by_id(id as i32);
let mut context = Context::new(); let mut context = Context::new();
context.insert("posts", &[post]); context.insert("posts", &[post]);
@ -109,7 +118,22 @@ async fn blog_by_id(web::Path(post_id): web::Path<std::string::String>) -> impl
#[get("/blog/edit")] #[get("/blog/edit")]
async fn blog_edit() -> impl Responder { async fn blog_edit() -> impl Responder {
"edit" let root_path = config::get_from_env("ROOT_PATH", true);
let mut context = Context::new();
context.insert("posts", &db::get_all_posts());
// one-off render blog template with context
let result = Tera::one_off(
&(std::fs::read_to_string(root_path + "/templates/edit.html")
.unwrap_or_else(|e| panic!("Error, couldn't load edit template.\n{}", e))
.as_str()),
&context,
false,
)
.unwrap_or_else(|e| panic!("Error, couldn't render submit template.\n{}", e));
return HttpResponse::Ok().content_type("text/html").body(result);
} }
#[get("/blog/edit/{post_id}")] #[get("/blog/edit/{post_id}")]
@ -118,7 +142,7 @@ async fn blog_edit_by_id(web::Path(post_id): web::Path<std::string::String>) ->
if valid { if valid {
let root_path = config::get_from_env("ROOT_PATH", true); let root_path = config::get_from_env("ROOT_PATH", true);
let mut post = get_post_by_id(id as i32); let mut post = db::get_post_by_id(id as i32);
post.title = replace_br_tags(&post.title); post.title = replace_br_tags(&post.title);
post.body = replace_br_tags(&post.body); post.body = replace_br_tags(&post.body);