ryuk-cli 0.1.0

The `ryuk` command: scaffold a Ryuk app (axum, SeaORM, Inertia/Svelte), generate controllers, models, jobs and mails, run migrations and the dev server.
use super::AppError;
use crate::{AppState, models::post};
use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
};
use ryuk::{
    auth::Auth,
    inertia::{self, Inertia},
    validation::Form,
};
use sea_orm::{ActiveModelTrait, ActiveValue::Set, ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter};
use serde::Deserialize;
use serde_json::json;
use ryuk::session::Session;
use utoipa::ToSchema;
use validator::Validate;

#[derive(Deserialize, Validate, ToSchema)]
pub struct PostForm {
    #[validate(length(min = 1, message = "Title is required"))]
    title: String,
    body: String,
}

/// Only the owner's posts are visible.
async fn owned(db: &DatabaseConnection, uid: i64, id: i64) -> Result<Option<post::Model>, AppError> {
    Ok(post::Entity::find_by_id(id)
        .filter(post::Column::UserId.eq(uid))
        .one(db)
        .await?)
}

fn not_found() -> Response {
    StatusCode::NOT_FOUND.into_response()
}

#[utoipa::path(get, path = "/posts", responses((status = 200, description = "Your posts")))]
pub async fn index(State(s): State<AppState>, Auth(uid): Auth, inertia: Inertia) -> Result<Response, AppError> {
    let posts = post::Entity::find()
        .filter(post::Column::UserId.eq(uid))
        .all(&s.db)
        .await?;
    Ok(inertia.render("Posts/Index", json!({ "posts": posts })))
}

#[utoipa::path(get, path = "/posts/create", responses((status = 200, description = "New post form")))]
pub async fn create(_: Auth, inertia: Inertia) -> Response {
    inertia.render("Posts/Create", json!({}))
}

#[utoipa::path(post, path = "/posts", request_body = PostForm,
    responses((status = 303, description = "Redirect to the post list")))]
pub async fn store(
    State(s): State<AppState>,
    Auth(uid): Auth,
    session: Session,
    Form(f): Form<PostForm>,
) -> Result<Response, AppError> {
    post::ActiveModel {
        user_id: Set(uid),
        title: Set(f.title),
        body: Set(f.body),
        ..Default::default()
    }
    .insert(&s.db)
    .await?;
    inertia::flash(&session, "success", "Post created.").await;
    Ok(inertia::redirect("/posts"))
}

#[utoipa::path(get, path = "/posts/{id}/edit", params(("id" = i64, Path, description = "Post id")),
    responses((status = 200, description = "Edit form"), (status = 404, description = "Not found")))]
pub async fn edit(
    State(s): State<AppState>,
    Auth(uid): Auth,
    Path(id): Path<i64>,
    inertia: Inertia,
) -> Result<Response, AppError> {
    Ok(match owned(&s.db, uid, id).await? {
        Some(p) => inertia.render("Posts/Edit", json!({ "post": p })),
        None => not_found(),
    })
}

#[utoipa::path(put, path = "/posts/{id}", params(("id" = i64, Path, description = "Post id")), request_body = PostForm,
    responses((status = 303, description = "Redirect to the post list"), (status = 404, description = "Not found")))]
pub async fn update(
    State(s): State<AppState>,
    Auth(uid): Auth,
    Path(id): Path<i64>,
    session: Session,
    Form(f): Form<PostForm>,
) -> Result<Response, AppError> {
    let Some(p) = owned(&s.db, uid, id).await? else {
        return Ok(not_found());
    };
    let mut a: post::ActiveModel = p.into();
    a.title = Set(f.title);
    a.body = Set(f.body);
    a.update(&s.db).await?;
    inertia::flash(&session, "success", "Post updated.").await;
    Ok(inertia::redirect("/posts"))
}

#[utoipa::path(delete, path = "/posts/{id}", params(("id" = i64, Path, description = "Post id")),
    responses((status = 303, description = "Redirect to the post list"), (status = 404, description = "Not found")))]
pub async fn destroy(
    State(s): State<AppState>,
    Auth(uid): Auth,
    Path(id): Path<i64>,
    session: Session,
) -> Result<Response, AppError> {
    if owned(&s.db, uid, id).await?.is_none() {
        return Ok(not_found());
    }
    post::Entity::delete_by_id(id).exec(&s.db).await?;
    inertia::flash(&session, "success", "Post deleted.").await;
    Ok(inertia::redirect("/posts"))
}