# {{app_name}}
A JSON API built with [Chyabrung](https://github.com/Chyabrung/chyabrung) 🥁.
## Run it
```sh
chy dev # http://127.0.0.1:2007, rebuilds and restarts on every save
# API docs (Swagger UI): http://127.0.0.1:2007/docs
cargo test # run the tests in tests/
chy build # optimized release build
```
## Where things go
```
{{app_name}}/
├── src/
│ ├── main.rs starts the app (rarely edited)
│ ├── lib.rs wires everything together: state, middleware, routes
│ ├── routes/ ★ every URL of the app: start here
│ │ ├── web.rs pages for browsers (/)
│ │ └── api.rs the JSON API (/api/...) and the WebSocket
│ ├── controllers/ handlers that answer requests, one file per feature
│ │ ├── auth_controller.rs register, login, me
│ │ ├── post_controller.rs index, store, show, update, destroy
│ │ ├── stats_controller.rs
│ │ ├── upload_controller.rs
│ │ └── realtime_controller.rs Server-Sent Events and WebSocket
│ ├── models/ one struct per database table (User, Post)
│ ├── mail/ one struct per kind of email (WelcomeMail)
│ ├── requests/ incoming data and its validation rules
│ ├── responses/ how models look in the JSON output (PostResource, UserResource)
│ └── middleware/ code that runs before/after handlers
├── templates/mail/ email designs: layout.html and one .html per email
├── migrations/ Rust files that create and change tables (up / down)
├── database/seeds/ sample data for development
├── public/ static files, served at /assets/...
├── storage/public/ user uploads (created automatically, not in git)
├── tests/ automated tests
├── .env secrets and local settings (not in git)
├── .env.example the same settings without secrets (in git)
└── chyabrung.toml app settings: name, port, database, deploy
```
Each `mod.rs` lists its folder's files; add a file with a `chy make:*`
command and it is listed for you.
## Models
A model is a struct with `#[model]` on top. Each field is a column, and
relations are fields too:
```rust
#[model]
pub struct Post {
pub id: i64,
pub user_id: i64,
pub title: String,
pub created_at: Option<Timestamp>,
pub updated_at: Option<Timestamp>,
#[belongs_to]
pub author: Option<User>,
}
let post = Post::find(1).await?;
let author = post.author().first().await?;
let posts = Post::with(&["author"]).latest().get().await?;
```
The table name (`posts`), the key (`id`) and the relation columns
(`user_id`) follow from the names. `created_at` and `updated_at` are filled
in for you. `#[model(guarded = ["role"])]` on `User` keeps `role` out of
`create(&input)`. See the database guide for every option.
## How a request flows
```
browser / client
│ GET /api/posts/1
▼
routes/api.rs finds the handler for this URL
▼
middleware logging, CORS, auth... (src/lib.rs)
▼
requests/ checks the input (422 with messages if invalid)
▼
controllers/ PostController::show
▼
models/ Post::find(1) → database
▼
responses/ PostResource picks the fields clients see
▼
JSON response
```
## Adding a feature: comments
One command writes the whole feature and connects it:
```sh
chy make:resource Comment --fields "body:text,post_id:int,approved:bool"
chy migrate # create the table
cargo test # includes the new tests/comment.rs
```
It creates:
| `src/models/comment.rs` | the `Comment` model |
| `migrations/..._create_comments_table.rs` | the table |
| `src/requests/comment.rs` | `CommentRequest` with validation rules |
| `src/responses/comment_resource.rs` | `CommentResource`: the fields clients see |
| `src/controllers/comment_controller.rs` | `CommentController` with index, store, show, update, destroy |
| `src/routes/api.rs` | `route.resource("/comments", CommentController)` |
| `tests/comment.rs` | a create/read/update/delete test |
Field types: `string`, `text`, `int`, `float`, `bool`; add `?` for an optional
column (`bio:text?`). Without `--fields` you get one `name` column. Then edit
the files as you like: for example add a `user: Auth` argument to a
handler to require a logged-in user.
Smaller generators exist for single pieces: `chy make:model Comment --fields "body:text" -m`,
`chy make:controller CommentController`, `chy make:migration add_bio_to_users`.
## API docs
`/docs` shows Swagger UI and `/openapi.json` the OpenAPI 3.1 spec, generated
from the routes when the app starts. For `#[controller]` methods,
the handler's doc comment becomes the summary, and its arguments
document the request body (`Json<PostRequest>`), query (`Query<PageQuery>`),
path parameters, login (`Auth`) and validation (`422`). Types in `requests/`
and `models/` describe themselves; for other types add `#[derive(ToSchema)]`.
## Endpoints
| `POST` | `/api/auth/register` | create an account, returns a token |
| `POST` | `/api/auth/login` | log in, returns a token |
| `GET` | `/api/me` | the logged-in user (send `Authorization: Bearer <token>`) |
| `GET` | `/api/posts` | published posts (`?page=1&per_page=10`) |
| `POST` | `/api/posts` | create a post (logged in) |
| `GET` | `/api/posts/{id}` | one post |
| `PUT` | `/api/posts/{id}` | edit your post |
| `DELETE` | `/api/posts/{id}` | delete your post |
| `GET` | `/api/stats` | counts, cached for a minute |
| `POST` | `/api/upload` | upload a file (logged in, multipart) |
| `GET` | `/api/events` | live events (Server-Sent Events) |
| `GET` | `/ws` | WebSocket echo |
| `GET` | `/docs` | API docs (Swagger UI), from `/openapi.json` |