chyabrung-cli 0.2.4

The `chy` command line tool for Chyabrung: scaffolding, dev server with hot reload, builds, generators, migrations and one-command deploys
use super::UserResource;
use crate::models::Post;
use chyabrung::prelude::*;

/// How a post looks in the API.
#[resource(Post)]
pub struct PostResource;

impl JsonResource for PostResource {
    fn to_array(&self) -> JsonValue {
        json!({
            "id": self.id,
            "title": self.title,
            "body": self.body,
            "excerpt": excerpt(&self.body),                        // computed, not a column
            "published": self.published,
            "author": UserResource::when_loaded(&self.author),     // only when loaded with .with(&["author"])
            "created_at": self.created_at,
            "updated_at": self.updated_at,
        })
    }
}

/// The first 120 characters of the body.
fn excerpt(body: &str) -> String {
    let mut short: String = body.chars().take(120).collect();
    if body.chars().count() > 120 {
        short.push('…');
    }
    short
}