chyabrung-cli 0.2.0

The `chy` command line tool for Chyabrung: scaffolding, dev server with hot reload, builds, generators, migrations and one-command deploys
//! Create, read, update and delete posts.
//!
//! A controller groups the routes of one feature under a prefix, like a
//! NestJS `@Controller('posts')`: every method with a `#[get]`, `#[post]`, ...
//! attribute is a route. It is mounted in `src/routes.rs`, inside `/api`.

use crate::models::Post;
use crate::requests::{PageQuery, PostRequest};
use chyabrung::prelude::*;

pub struct PostController;

#[controller("/posts")]
impl PostController {
    /// Published posts, newest first (`?page=1&per_page=10`).
    #[get("/")]
    async fn index(State(db): State<Db>, Valid(Query(q)): Valid<Query<PageQuery>>) -> Result<Json<Page<Post>>> {
        let page = Post::query(&db)
            .where_("published", true)
            .latest()
            .paginate(q.page.unwrap_or(1), q.per_page.unwrap_or(10))
            .await?;
        Ok(Json(page))
    }

    /// Create a post (logged in).
    #[post("/")]
    async fn store(
        Auth(user): Auth,
        State(db): State<Db>,
        State(cache): State<Cache>,
        Valid(Json(input)): Valid<Json<PostRequest>>,
    ) -> Result<(StatusCode, Json<Post>)> {
        let post = Post::create(
            &db,
            &json!({
                "user_id": user.id.parse::<i64>().unwrap_or_default(),
                "title": input.title,
                "body": input.body,
                "published": input.published,
            }),
        )
        .await?;
        cache.forget("stats").await?;
        Ok((StatusCode::CREATED, Json(post)))
    }

    /// One post (`404` if it does not exist).
    #[get("/:id", name = "posts.show")]
    async fn show(State(db): State<Db>, Path(id): Path<i64>) -> Result<Json<Post>> {
        Ok(Json(Post::find(&db, id).await?))
    }

    /// Update a post (its author or an editor).
    #[put("/:id")]
    async fn update(
        Auth(user): Auth,
        State(db): State<Db>,
        Path(id): Path<i64>,
        Valid(Json(input)): Valid<Json<PostRequest>>,
    ) -> Result<Json<Post>> {
        let mut post = Post::find(&db, id).await?;
        if !post.can_be_changed_by(&user, "posts.update") {
            return Err(Error::forbidden("You can only change your own posts."));
        }
        post.title = input.title;
        post.body = input.body;
        post.published = input.published;
        post.save(&db).await?;
        Ok(Json(post.refresh(&db).await?))
    }

    /// Delete a post (its author or an admin).
    #[delete("/:id")]
    async fn destroy(
        Auth(user): Auth,
        State(db): State<Db>,
        State(cache): State<Cache>,
        Path(id): Path<i64>,
    ) -> Result<StatusCode> {
        let post = Post::find(&db, id).await?;
        if !post.can_be_changed_by(&user, "posts.delete") {
            return Err(Error::forbidden("You can only change your own posts."));
        }
        post.delete(&db).await?;
        cache.forget("stats").await?;
        Ok(StatusCode::NO_CONTENT)
    }
}