|
| 1 | +use axum::{ |
| 2 | + Json, |
| 3 | + extract::{Path, State}, |
| 4 | + http::StatusCode, |
| 5 | +}; |
| 6 | +use uuid::Uuid; |
| 7 | +use validator::Validate; |
| 8 | + |
| 9 | +use crate::{ |
| 10 | + config::AppState, |
| 11 | + dtos::project_dto::{CreateProjectPayload, ProjectResponse, UpdateProjectPayload}, |
| 12 | + middleware::auth::AuthUser, |
| 13 | + models::Project, |
| 14 | + utils::{api_error::ApiError, format_validation_errors, response::ApiResponse}, |
| 15 | +}; |
| 16 | + |
| 17 | +/** |
| 18 | + * Controller function to create a new project within a workspace. Validates the input payload, checks user authentication, and interacts with the database to persist the new project. Returns a structured API response with the created project details or appropriate error messages. |
| 19 | + * Path: POST /api/v1/projects |
| 20 | + */ |
| 21 | +pub async fn create_project( |
| 22 | + State(state): State<AppState>, |
| 23 | + AuthUser(user): AuthUser, |
| 24 | + Json(payload): Json<CreateProjectPayload>, |
| 25 | +) -> Result<Json<ApiResponse<ProjectResponse>>, ApiError> { |
| 26 | + // logging the project creation attempt with the email (but not the password) |
| 27 | + tracing::info!( |
| 28 | + "Attempting to create project with name: {} for workspace: {} by user: {}", |
| 29 | + payload.name, |
| 30 | + payload.workspace_id, |
| 31 | + user.email |
| 32 | + ); |
| 33 | + |
| 34 | + // Validate the input payload |
| 35 | + payload.validate().map_err(|e| { |
| 36 | + let error_messages = format_validation_errors(&e); |
| 37 | + tracing::error!("Validation errors: {}", error_messages); |
| 38 | + ApiError::BadRequest(error_messages) |
| 39 | + })?; |
| 40 | + |
| 41 | + // create the project in the database |
| 42 | + let project = sqlx::query_as::<_, Project>( |
| 43 | + "INSERT INTO projects (workspace_id, name, description) |
| 44 | + VALUES ($1, $2, $3) |
| 45 | + RETURNING *", |
| 46 | + ) |
| 47 | + .bind(payload.workspace_id) |
| 48 | + .bind(&payload.name) |
| 49 | + .bind(&payload.description) |
| 50 | + .fetch_one(&state.db) |
| 51 | + .await |
| 52 | + .map_err(|_| ApiError::InternalServerError("Failed to create project".into()))?; |
| 53 | + |
| 54 | + // return the created project in the response |
| 55 | + Ok(Json(ApiResponse::new( |
| 56 | + true, |
| 57 | + StatusCode::CREATED, |
| 58 | + "Project created successfully", |
| 59 | + Some(ProjectResponse { |
| 60 | + id: project.id, |
| 61 | + workspace_id: project.workspace_id, |
| 62 | + name: project.name, |
| 63 | + description: project.description, |
| 64 | + created_at: project.created_at, |
| 65 | + updated_at: project.updated_at, |
| 66 | + }), |
| 67 | + ))) |
| 68 | +} |
| 69 | + |
| 70 | +/** |
| 71 | + * Controller function to update an existing project. Validates the input payload, checks user authentication, verifies project existence, and updates the project details in the database. Returns a structured API response with the updated project details or appropriate error messages. |
| 72 | + * Path: PUT /api/v1/projects/{id} |
| 73 | + */ |
| 74 | +pub async fn update_project( |
| 75 | + State(state): State<AppState>, |
| 76 | + AuthUser(user): AuthUser, |
| 77 | + Path(project_id): Path<Uuid>, |
| 78 | + Json(payload): Json<UpdateProjectPayload>, |
| 79 | +) -> Result<Json<ApiResponse<ProjectResponse>>, ApiError> { |
| 80 | + // logging the project update attempt with the email (but not the password) |
| 81 | + tracing::info!( |
| 82 | + "Attempting to update project with id: {} by user: {}", |
| 83 | + project_id, |
| 84 | + user.email |
| 85 | + ); |
| 86 | + |
| 87 | + // Validate the input payload |
| 88 | + payload.validate().map_err(|e| { |
| 89 | + let error_messages = format_validation_errors(&e); |
| 90 | + tracing::error!("Validation errors: {}", error_messages); |
| 91 | + ApiError::BadRequest(error_messages) |
| 92 | + })?; |
| 93 | + |
| 94 | + // Check if the project exists |
| 95 | + let existing_project = sqlx::query_as::<_, Project>("SELECT * FROM projects WHERE id = $1") |
| 96 | + .bind(project_id) |
| 97 | + .fetch_optional(&state.db) |
| 98 | + .await |
| 99 | + .map_err(|_| ApiError::InternalServerError("Failed to query project".into()))?; |
| 100 | + |
| 101 | + // If the project does not exist, return a 404 error |
| 102 | + if existing_project.is_none() { |
| 103 | + tracing::warn!("Project with id: {} not found", project_id); |
| 104 | + return Err(ApiError::NotFound("Project not found".into())); |
| 105 | + } |
| 106 | + |
| 107 | + // Update the project in the database |
| 108 | + let updated_project = sqlx::query_as::<_, Project>( |
| 109 | + "UPDATE projects SET name = COALESCE($1, name), description = COALESCE($2, description), updated_at = NOW() |
| 110 | + WHERE id = $3 |
| 111 | + RETURNING *", |
| 112 | + ) |
| 113 | + .bind(&payload.name) |
| 114 | + .bind(&payload.description) |
| 115 | + .bind(project_id) |
| 116 | + .fetch_one(&state.db) |
| 117 | + .await |
| 118 | + .map_err(|_| ApiError::InternalServerError("Failed to update project".into()))?; |
| 119 | + |
| 120 | + // return the updated project in the response |
| 121 | + Ok(Json(ApiResponse::new( |
| 122 | + true, |
| 123 | + StatusCode::OK, |
| 124 | + "Project updated successfully", |
| 125 | + Some(ProjectResponse { |
| 126 | + id: updated_project.id, |
| 127 | + workspace_id: updated_project.workspace_id, |
| 128 | + name: updated_project.name, |
| 129 | + description: updated_project.description, |
| 130 | + created_at: updated_project.created_at, |
| 131 | + updated_at: updated_project.updated_at, |
| 132 | + }), |
| 133 | + ))) |
| 134 | +} |
| 135 | + |
| 136 | +/** |
| 137 | + * Controller function to delete an existing project. Checks user authentication, verifies project existence, and deletes the project from the database. Returns a structured API response indicating success or appropriate error messages. |
| 138 | + * Path: DELETE /api/v1/projects/{id} |
| 139 | + */ |
| 140 | +pub async fn delete_project( |
| 141 | + State(state): State<AppState>, |
| 142 | + AuthUser(user): AuthUser, |
| 143 | + Path(project_id): Path<Uuid>, |
| 144 | +) -> Result<Json<ApiResponse<()>>, ApiError> { |
| 145 | + // logging the project deletion attempt with the email (but not the password) |
| 146 | + tracing::info!( |
| 147 | + "Attempting to delete project with id: {} by user: {}", |
| 148 | + project_id, |
| 149 | + user.email |
| 150 | + ); |
| 151 | + |
| 152 | + // Check if the project exists |
| 153 | + let existing_project = sqlx::query_as::<_, Project>("SELECT * FROM projects WHERE id = $1") |
| 154 | + .bind(project_id) |
| 155 | + .fetch_optional(&state.db) |
| 156 | + .await |
| 157 | + .map_err(|_| ApiError::InternalServerError("Failed to query project".into()))?; |
| 158 | + |
| 159 | + // If the project does not exist, return a 404 error |
| 160 | + if existing_project.is_none() { |
| 161 | + tracing::warn!("Project with id: {} not found", project_id); |
| 162 | + return Err(ApiError::NotFound("Project not found".into())); |
| 163 | + } |
| 164 | + |
| 165 | + // Delete the project from the database |
| 166 | + sqlx::query("DELETE FROM projects WHERE id = $1") |
| 167 | + .bind(project_id) |
| 168 | + .execute(&state.db) |
| 169 | + .await |
| 170 | + .map_err(|_| ApiError::InternalServerError("Failed to delete project".into()))?; |
| 171 | + |
| 172 | + // return a success response with no data |
| 173 | + Ok(Json(ApiResponse::new( |
| 174 | + true, |
| 175 | + StatusCode::OK, |
| 176 | + "Project deleted successfully", |
| 177 | + None, |
| 178 | + ))) |
| 179 | +} |
0 commit comments