#![allow(clippy::missing_errors_doc)] #![allow(clippy::unnecessary_struct_initialization)] #![allow(clippy::unused_async)] use loco_rs::prelude::*; use sea_orm::{sea_query::Order, QueryOrder}; use serde::{Deserialize, Serialize}; use crate::{ models::_entities::notes::{ActiveModel, Column, Entity, Model}, views, }; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Params { pub user_id: i64, pub title: Option, pub content: Option, } impl Params { fn update(&self, item: &mut ActiveModel) { item.user_id = Set(self.user_id); item.title = Set(self.title.clone()); item.content = Set(self.content.clone()); } } async fn load_item(ctx: &AppContext, id: i64) -> Result { let item = Entity::find_by_id(id).one(&ctx.db).await?; item.ok_or_else(|| Error::NotFound) } #[debug_handler] pub async fn list( ViewEngine(v): ViewEngine, State(ctx): State, ) -> Result { let item = Entity::find() .order_by(Column::Id, Order::Desc) .all(&ctx.db) .await?; views::note::list(&v, &item) } #[debug_handler] pub async fn new( ViewEngine(v): ViewEngine, State(_ctx): State, ) -> Result { views::note::create(&v) } #[debug_handler] pub async fn update( Path(id): Path, State(ctx): State, Json(params): Json, ) -> Result { let item = load_item(&ctx, id).await?; let mut item = item.into_active_model(); params.update(&mut item); let _ = item.update(&ctx.db).await?; format::render().redirect_with_header_key("HX-Redirect", "/notes") } #[debug_handler] pub async fn edit( Path(id): Path, ViewEngine(v): ViewEngine, State(ctx): State, ) -> Result { let item = load_item(&ctx, id).await?; views::note::edit(&v, &item) } #[debug_handler] pub async fn show( Path(id): Path, ViewEngine(v): ViewEngine, State(ctx): State, ) -> Result { let item = load_item(&ctx, id).await?; views::note::show(&v, &item) } #[debug_handler] pub async fn add(State(ctx): State, Json(params): Json) -> Result { let mut item = ActiveModel { ..Default::default() }; params.update(&mut item); let _ = item.insert(&ctx.db).await?; format::render().redirect_with_header_key("HX-Redirect", "/notes") } #[debug_handler] pub async fn remove(Path(id): Path, State(ctx): State) -> Result { load_item(&ctx, id).await?.delete(&ctx.db).await?; format::empty() } pub fn routes() -> Routes { Routes::new() .prefix("notes/") .add("/", get(list)) .add("/", post(add)) .add("new", get(new)) .add("{id}", get(show)) .add("{id}/edit", get(edit)) .add("{id}", delete(remove)) .add("{id}", put(update)) .add("{id}", patch(update)) }