Add note scaffold

This commit is contained in:
2026-07-26 14:45:55 +03:00
parent e376ed950b
commit d640ce35b6
20 changed files with 604 additions and 8 deletions
+113
View File
@@ -0,0 +1,113 @@
#![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<String>,
pub content: Option<String>,
}
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<Model> {
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<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
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<TeraView>,
State(_ctx): State<AppContext>,
) -> Result<Response> {
views::note::create(&v)
}
#[debug_handler]
pub async fn update(
Path(id): Path<i64>,
State(ctx): State<AppContext>,
Json(params): Json<Params>,
) -> Result<Response> {
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<i64>,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let item = load_item(&ctx, id).await?;
views::note::edit(&v, &item)
}
#[debug_handler]
pub async fn show(
Path(id): Path<i64>,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let item = load_item(&ctx, id).await?;
views::note::show(&v, &item)
}
#[debug_handler]
pub async fn add(State(ctx): State<AppContext>, Json(params): Json<Params>) -> Result<Response> {
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<i64>, State(ctx): State<AppContext>) -> Result<Response> {
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))
}