create recipe 2

This commit is contained in:
eraden 2024-10-31 08:40:04 +01:00
parent a3a8e32f14
commit b4e307496e
2 changed files with 50 additions and 21 deletions

View File

@ -7,6 +7,7 @@ use actix_web::web::{Data, Form, Path};
use actix_web::HttpMessage; use actix_web::HttpMessage;
use actix_web::{get, post, HttpRequest, HttpResponse, Responder}; use actix_web::{get, post, HttpRequest, HttpResponse, Responder};
use askama::Template; use askama::Template;
use askama_actix::TemplateToResponse;
use sea_orm::{prelude::*, QuerySelect}; use sea_orm::{prelude::*, QuerySelect};
use serde::Deserialize; use serde::Deserialize;
@ -62,6 +63,9 @@ struct RecipeForm {
ingeredients: String, ingeredients: String,
steps: String, steps: String,
tags: String, tags: String,
image_url: String,
time: Option<String>,
author: Option<String>,
error: Option<String>, error: Option<String>,
session: Option<User>, session: Option<User>,
page: Page, page: Page,
@ -287,6 +291,9 @@ async fn recipe_form(admin: Identity) -> RecipeForm {
ingeredients: "".into(), ingeredients: "".into(),
steps: "".into(), steps: "".into(),
tags: "".into(), tags: "".into(),
image_url: "".into(),
author: None,
time: None,
error: None, error: None,
session: admin.id().ok(), session: admin.id().ok(),
page: Page::Index, page: Page::Index,
@ -295,29 +302,45 @@ async fn recipe_form(admin: Identity) -> RecipeForm {
#[post("/create")] #[post("/create")]
async fn create_recipe( async fn create_recipe(
admin: Identity, _admin: Identity,
form: Form<RecipeForm>, form: Form<RecipeForm>,
db: Data<DatabaseConnection>, db: Data<DatabaseConnection>,
) -> RecipeForm { ) -> HttpResponse {
let form = form.into_inner(); let form = form.into_inner();
let mut failure = form.clone(); let mut failure = form.clone();
let title = form.title; match save_recipe(form, db.into_inner()).await {
Err(e) => {
failure.error = Some(e.to_string());
failure.to_response()
}
Ok(_) => HttpResponse::TemporaryRedirect()
.append_header(("location", "/"))
.finish(),
}
}
async fn save_recipe(form: RecipeForm, db: DatabaseConnection) -> Result<(), Error> {
use crate::entities::recipies::ActiveModel as RAM;
use sea_orm::ActiveValue::*;
let mut summary = String::new(); let mut summary = String::new();
let parser = pulldown_cmark::Parser::new(&form.summary); let parser = pulldown_cmark::Parser::new(&form.summary);
pulldown_cmark::html::push_html(&mut summary, parser); pulldown_cmark::html::push_html(&mut summary, parser);
let Ok(steps) = crate::utils::parse_steps(&form.steps, 0) else { let model = RAM {
failure.error = Some("Invalid steps list".into()); title: Set(form.title),
return failure; image_url: Set(form.image_url),
}; author: Set(None),
let Ok(ingeredients) = crate::utils::parse_steps(&form.ingeredients, 0) else { time: Set(None),
failure.error = Some("Invalid ingeredients list".into()); summary: Set(Some(summary)),
return failure; ..Default::default()
}; };
failure let steps = crate::utils::parse_steps(&form.steps, 0)?;
let ingeredients = crate::utils::parse_steps(&form.ingeredients, 0)?;
Ok(())
} }
#[get("/styles.css")] #[get("/styles.css")]

View File

@ -1,10 +1,11 @@
use crate::entities::recipe_ingeredients::ActiveModel as RIAM; use crate::entities::recipe_ingeredients::ActiveModel as RIAM;
use crate::entities::recipe_steps::ActiveModel as RSAM; use crate::entities::recipe_steps::ActiveModel as RSAM;
use crate::types::Error;
use crate::types::Error::*; use crate::types::Error::*;
use sea_orm::prelude::*; use sea_orm::prelude::*;
use sea_orm::ActivrValue::*; use sea_orm::ActiveValue::*;
pub fn parse_steps(s: &str, recipe_id: u64) -> Result<Vec<RSAM>, InvalidStepList> { pub fn parse_steps(s: &str, recipe_id: i32) -> Result<Vec<RSAM>, Error> {
s.lines() s.lines()
.filter(|s| !s.trim().is_empty()) .filter(|s| !s.trim().is_empty())
.try_fold(Vec::new(), |mut v, line| { .try_fold(Vec::new(), |mut v, line| {
@ -12,16 +13,15 @@ pub fn parse_steps(s: &str, recipe_id: u64) -> Result<Vec<RSAM>, InvalidStepList
match line.chars().next() { match line.chars().next() {
Some('*') => { Some('*') => {
let line = line.replacen("*", "", 1).trim();
v.push(RSAM { v.push(RSAM {
body: Set(line.to_string()), body: Set(line.replacen("*", "", 1).trim().to_string()),
recipe_id: Set(recipe_id), recipe_id: Set(recipe_id),
..Default::default() ..Default::default()
}); });
} }
Some('>') => { Some('>') => {
let line = line.replacen(">", "", 1).trim(); v.last_mut().ok_or(InvalidStepList)?.hint =
v.last_mut().ok_or(InvalidStepList)?.hint = Set(line.to_string()); Set(Some(line.replacen(">", "", 1).trim().to_string()));
} }
_ => return Err(InvalidStepList), _ => return Err(InvalidStepList),
}; };
@ -30,7 +30,7 @@ pub fn parse_steps(s: &str, recipe_id: u64) -> Result<Vec<RSAM>, InvalidStepList
}) })
} }
pub fn parse_ingenedients(s: &str, recipe_id: u64) -> Result<Vec<RIAM>, InvalidIngeredientList> { pub fn parse_ingenedients(s: &str, recipe_id: i32) -> Result<Vec<RIAM>, Error> {
s.lines() s.lines()
.map(|s| s.trim()) .map(|s| s.trim())
.filter(|s| !s.is_empty()) .filter(|s| !s.is_empty())
@ -43,7 +43,10 @@ pub fn parse_ingenedients(s: &str, recipe_id: u64) -> Result<Vec<RIAM>, InvalidI
0 | 1 => return Err(InvalidIngeredientList), 0 | 1 => return Err(InvalidIngeredientList),
// no unit // no unit
2 => { 2 => {
let qty = pieces.remove(0).parse().map_err(|_| InvalidIngeredientList); let qty = pieces
.remove(0)
.parse()
.map_err(|_| InvalidIngeredientList)?;
Ok(RIAM { Ok(RIAM {
recipe_id: Set(recipe_id), recipe_id: Set(recipe_id),
name: Set(pieces.join(" ")), name: Set(pieces.join(" ")),
@ -52,12 +55,15 @@ pub fn parse_ingenedients(s: &str, recipe_id: u64) -> Result<Vec<RIAM>, InvalidI
}) })
} }
_ => { _ => {
let qty = pieces.remove(0).parse().map_err(|_| InvalidIngeredientList); let qty = pieces
.remove(0)
.parse()
.map_err(|_| InvalidIngeredientList)?;
let unit = pieces.remove(0); let unit = pieces.remove(0);
Ok(RIAM { Ok(RIAM {
recipe_id: Set(recipe_id), recipe_id: Set(recipe_id),
name: Set(pieces.join(" ")), name: Set(pieces.join(" ")),
unit: Set(unit), unit: Set(unit.to_string()),
qty: Set(qty), qty: Set(qty),
..Default::default() ..Default::default()
}) })