peer-group-grading/crates/backend/src/controller/project.rs
2025-04-02 21:22:17 +02:00

81 lines
1.9 KiB
Rust

use actix_web::{Responder, Result, delete, get, post, put, web};
use sea_orm::prelude::Uuid;
use serde::Deserialize;
use crate::db::Database;
use crate::error::ApiError;
#[derive(Deserialize)]
struct CreateProject {
name: String,
}
#[derive(Deserialize)]
struct UpdateProject {
id: Uuid,
name: String,
}
pub fn setup(cfg: &mut actix_web::web::ServiceConfig) {
cfg.service(get_project)
.service(get_projects)
.service(create_project)
.service(delete_project);
}
#[get("")]
async fn get_projects(
db: web::Data<Database>,
) -> Result<web::Json<Vec<entity::project::Model>>, ApiError> {
let projects = db.get_projects().await?;
Ok(web::Json(projects))
}
#[get("/{id}")]
async fn get_project(
db: web::Data<Database>,
path: web::Path<Uuid>,
) -> Result<web::Json<entity::project::Model>, ApiError> {
let id = path.into_inner();
let project = db.get_project(&id).await?;
Ok(web::Json(project.unwrap()))
}
#[post("")]
async fn create_project(
db: web::Data<Database>,
create_project_struct: web::Json<CreateProject>,
) -> Result<web::Json<entity::project::Model>, ApiError> {
let result = db.create_project(&create_project_struct.name).await?;
Ok(web::Json(result))
}
#[put("")]
async fn change_project(
db: web::Data<Database>,
update_project_struct: web::Json<UpdateProject>,
) -> Result<web::Json<entity::project::Model>, ApiError> {
let updated_project = db
.update_project(update_project_struct.into_inner())
.await?;
Ok(web::Json(updated_project))
}
#[delete("/{id}")]
async fn delete_project(
db: web::Data<Database>,
path: web::Path<Uuid>,
) -> Result<web::Json<String>, ApiError> {
let id = path.into_inner();
let result = db.delete_project(&id).await?;
Ok(web::Json(format!(
"Successfully deleted {} project/s with the id: {}",
result.rows_affected, id
)))
}