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::owner;
use crate::{AppState, models::post};
use axum::{
    Json,
    extract::{Path, State},
    http::StatusCode,
};
use ryuk::api::{ApiAuth, ApiError};
use sea_orm::{ActiveModelTrait, ActiveValue::Set, ColumnTrait, EntityTrait, QueryFilter};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use validator::Validate;

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

#[derive(Serialize, ToSchema)]
pub struct PostOut {
    id: i64,
    title: String,
    body: String,
}

impl From<post::Model> for PostOut {
    fn from(p: post::Model) -> Self {
        PostOut { id: p.id, title: p.title, body: p.body }
    }
}

fn check(i: &PostInput) -> Result<(), ApiError> {
    i.validate().map_err(|e| {
        let errs = e.field_errors().into_iter().map(|(f, v)| {
            let m = v.iter().map(|e| e.message.as_deref().unwrap_or(&e.code).to_string());
            (f.to_string(), m.collect())
        });
        ApiError::validation(errs.collect())
    })
}

/// A key only ever sees its owner's posts.
async fn find(s: &AppState, uid: i64, id: i64) -> Result<post::Model, ApiError> {
    post::Entity::find_by_id(id)
        .filter(post::Column::UserId.eq(uid))
        .one(&s.db)
        .await?
        .ok_or_else(ApiError::not_found)
}

#[utoipa::path(get, path = "/posts", security(("api_key" = []), ("oauth2" = ["posts:read"])),
    responses((status = 200, body = Vec<PostOut>, description = "Your posts"), (status = 401, description = "Missing or invalid credential"), (status = 403, description = "Missing scope posts:read")))]
pub async fn index(State(s): State<AppState>, ApiAuth(p): ApiAuth) -> Result<Json<Vec<PostOut>>, ApiError> {
    p.require("posts:read")?;
    let rows = post::Entity::find().filter(post::Column::UserId.eq(owner(&p)?)).all(&s.db).await?;
    Ok(Json(rows.into_iter().map(Into::into).collect()))
}

#[utoipa::path(post, path = "/posts", request_body = PostInput, security(("api_key" = []), ("oauth2" = ["posts:write"])),
    responses((status = 201, body = PostOut, description = "Created"), (status = 401, description = "Missing or invalid credential"), (status = 403, description = "Missing scope posts:write"), (status = 422, description = "Validation failed")))]
pub async fn store(
    State(s): State<AppState>,
    ApiAuth(p): ApiAuth,
    Json(i): Json<PostInput>,
) -> Result<(StatusCode, Json<PostOut>), ApiError> {
    p.require("posts:write")?;
    let uid = owner(&p)?;
    check(&i)?;
    let row = post::ActiveModel { user_id: Set(uid), title: Set(i.title), body: Set(i.body), ..Default::default() }
        .insert(&s.db)
        .await?;
    Ok((StatusCode::CREATED, Json(row.into())))
}

#[utoipa::path(get, path = "/posts/{id}", params(("id" = i64, Path, description = "Post id")),
    security(("api_key" = []), ("oauth2" = ["posts:read"])),
    responses((status = 200, body = PostOut, description = "The post"), (status = 404, description = "Not found")))]
pub async fn show(State(s): State<AppState>, ApiAuth(p): ApiAuth, Path(id): Path<i64>) -> Result<Json<PostOut>, ApiError> {
    p.require("posts:read")?;
    Ok(Json(find(&s, owner(&p)?, id).await?.into()))
}

#[utoipa::path(put, path = "/posts/{id}", params(("id" = i64, Path, description = "Post id")), request_body = PostInput,
    security(("api_key" = []), ("oauth2" = ["posts:write"])),
    responses((status = 200, body = PostOut, description = "Updated"), (status = 404, description = "Not found"), (status = 422, description = "Validation failed")))]
pub async fn update(
    State(s): State<AppState>,
    ApiAuth(p): ApiAuth,
    Path(id): Path<i64>,
    Json(i): Json<PostInput>,
) -> Result<Json<PostOut>, ApiError> {
    p.require("posts:write")?;
    let row = find(&s, owner(&p)?, id).await?;
    check(&i)?;
    let mut a: post::ActiveModel = row.into();
    a.title = Set(i.title);
    a.body = Set(i.body);
    Ok(Json(a.update(&s.db).await?.into()))
}

#[utoipa::path(delete, path = "/posts/{id}", params(("id" = i64, Path, description = "Post id")),
    security(("api_key" = []), ("oauth2" = ["posts:write"])),
    responses((status = 204, description = "Deleted"), (status = 404, description = "Not found")))]
pub async fn destroy(State(s): State<AppState>, ApiAuth(p): ApiAuth, Path(id): Path<i64>) -> Result<StatusCode, ApiError> {
    p.require("posts:write")?;
    find(&s, owner(&p)?, id).await?;
    post::Entity::delete_by_id(id).exec(&s.db).await?;
    Ok(StatusCode::NO_CONTENT)
}