// src/controllers/todos.rs
use kit::{json_response, Request, Response};
use kit::database::{Model, ModelMut};
use crate::models::todos::{Entity as Todos, ActiveModel, Model as Todo};
use sea_orm::ActiveValue::Set;
// GET /todos
pub async fn index(_req: Request) -> Response {
match Todos::all().await {
Ok(todos) => json_response!({ "todos": todos }),
Err(e) => json_response!({ "error": e.to_string() }),
}
}
// GET /todos/:id
pub async fn show(req: Request) -> Response {
let id: i32 = req.param("id").unwrap().parse().unwrap();
match Todos::find_or_fail(id).await {
Ok(todo) => json_response!({ "todo": todo }),
Err(_) => json_response!({ "error": "Todo not found" }),
}
}
// POST /todos
pub async fn store(req: Request) -> Response {
// Parse request body for title
let title = "New Todo".to_string();
let new_todo = ActiveModel {
title: Set(title),
completed: Set(false),
..Default::default()
};
match Todos::insert_one(new_todo).await {
Ok(result) => json_response!({ "id": result.last_insert_id }),
Err(e) => json_response!({ "error": e.to_string() }),
}
}
// PUT /todos/:id
pub async fn update(req: Request) -> Response {
let id: i32 = req.param("id").unwrap().parse().unwrap();
// Find existing record
let existing = Todos::find_or_fail(id).await.unwrap();
// Convert to active model and update
let mut todo: ActiveModel = existing.into();
todo.completed = Set(true);
match Todos::update_one(todo).await {
Ok(updated) => json_response!({ "todo": updated }),
Err(e) => json_response!({ "error": e.to_string() }),
}
}
// DELETE /todos/:id
pub async fn destroy(req: Request) -> Response {
let id: i32 = req.param("id").unwrap().parse().unwrap();
match Todos::delete_by_pk(id).await {
Ok(result) => json_response!({
"deleted": result.rows_affected > 0
}),
Err(e) => json_response!({ "error": e.to_string() }),
}
}