Skip to content

Commit

Permalink
This should actually be removing ApiResponse (#354)
Browse files Browse the repository at this point in the history
  • Loading branch information
TheKrol authored Jan 30, 2025
1 parent a4c4407 commit 178e3f6
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 132 deletions.
110 changes: 22 additions & 88 deletions backend/src/handlers_prelude/github_handlers.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::handlers_prelude::eyre_to_axum_err;
use crate::handlers_prelude::ApiError;
use crate::AppState;
use axum::routing::{get, post, put};
use axum::{
Expand All @@ -11,20 +11,6 @@ use serde::{Deserialize, Serialize};
use serde_json::Value;
use tracing::{error, info};

/// General API response structure
#[derive(Serialize, Debug)]
pub struct ApiResponse<T> {
pub status: String,
pub message: String,
pub data: Option<T>,
}

/// Error response structure
#[derive(Serialize, Debug)]
pub struct ApiErrorResponse {
pub error: String,
}

/// Represents the structure for a pull request creation response
#[derive(Serialize, Debug)]
pub struct CreatePRData {
Expand Down Expand Up @@ -72,13 +58,9 @@ pub struct UpdatePRRequest {
/// Fetches the list of branches from a GitHub repository.
pub async fn list_branches_handler(
State(state): State<AppState>,
) -> Result<(StatusCode, Json<ApiResponse<BranchesData>>), (StatusCode, String)> {
) -> Result<Json<BranchesData>, ApiError> {
// Fetch the branch details from GitHub using the GitHubClient instance
let branch_details = state
.gh_client
.list_branches()
.await
.map_err(eyre_to_axum_err)?;
let branch_details = state.gh_client.list_branches().await?;

// Extract branch names and handle protection status if needed
let branches: Vec<String> = branch_details
Expand All @@ -93,23 +75,16 @@ pub async fn list_branches_handler(
})
.collect();

// Return success response
// Wrap the branches data in the BranchesData struct and return as JSON
info!("Branches fetched successfully.");
Ok((
StatusCode::OK,
Json(ApiResponse {
status: "success".to_string(),
message: "Branches fetched successfully".to_string(),
data: Some(BranchesData { branches }),
}),
))
Ok(Json(BranchesData { branches }))
}

/// Handler to create a pull request from a specified head branch to a base branch.
pub async fn create_pull_request_handler(
State(state): State<AppState>,
Json(payload): Json<CreatePRRequest>,
) -> Result<(StatusCode, Json<ApiResponse<CreatePRData>>), (StatusCode, String)> {
) -> Result<(StatusCode, Json<CreatePRData>), (StatusCode, String)> {
// Create the pull request using the new method from GitHubClient
match state
.gh_client
Expand All @@ -128,14 +103,7 @@ pub async fn create_pull_request_handler(
"Pull request created successfully from {} to {}",
payload.head_branch, payload.base_branch
);
Ok((
StatusCode::CREATED,
Json(ApiResponse {
status: "success".to_string(),
message: "Pull request created successfully".to_string(),
data: Some(CreatePRData { pull_request_url }),
}),
))
Ok((StatusCode::CREATED, Json(CreatePRData { pull_request_url })))
}
Err(err) => {
// Handle error case in creating the pull request
Expand All @@ -149,7 +117,7 @@ pub async fn create_pull_request_handler(
pub async fn update_pull_request_handler(
State(state): State<AppState>,
Json(payload): Json<UpdatePRRequest>,
) -> Result<(StatusCode, Json<ApiResponse<String>>), (StatusCode, String)> {
) -> Result<(StatusCode, Json<String>), (StatusCode, String)> {
// Update the pull request
match state
.gh_client
Expand All @@ -164,14 +132,7 @@ pub async fn update_pull_request_handler(
{
Ok(updated_pr_url) => {
info!("Pull request #{} updated successfully", payload.pr_number);
Ok((
StatusCode::OK,
Json(ApiResponse {
status: "success".to_string(),
message: "Pull request updated successfully.".to_string(),
data: Some(updated_pr_url),
}),
))
Ok((StatusCode::OK, Json(updated_pr_url)))
}
Err(err) => {
let error_message = format!("Failed to update pull request: {:?}", err);
Expand All @@ -184,18 +145,14 @@ pub async fn update_pull_request_handler(
pub async fn close_pull_request_handler(
State(state): State<AppState>,
Path(pr_number): Path<u64>,
) -> Result<(StatusCode, Json<ApiResponse<String>>), (StatusCode, String)> {
) -> Result<(StatusCode, Json<String>), (StatusCode, String)> {
// Attempt to close the pull request
match state.gh_client.close_pull_request(pr_number).await {
Ok(_) => {
info!("Pull request #{} closed successfully", pr_number);
Ok((
StatusCode::OK,
Json(ApiResponse {
status: "success".to_string(),
message: "Pull request closed successfully.".to_string(),
data: Some(format!("Pull request #{} closed.", pr_number)),
}),
Json(format!("Pull request #{} closed.", pr_number)),
))
}
Err(err) => {
Expand Down Expand Up @@ -234,18 +191,17 @@ pub async fn checkout_or_create_branch_handler(
pub async fn pull_handler(
State(state): State<AppState>,
Path(branch): Path<String>,
) -> Result<(StatusCode, Json<ApiResponse<String>>), (StatusCode, String)> {
) -> Result<(StatusCode, Json<String>), (StatusCode, String)> {
// Attempt to pull the latest changes for the specified branch
match state.git.git_pull_branch(&branch) {
Ok(_) => {
info!("Repository pulled successfully for branch '{}'.", branch);
Ok((
StatusCode::OK,
Json(ApiResponse {
status: "success".to_string(),
message: format!("Repository pulled successfully for branch '{}'.", branch),
data: Some("Pull operation completed.".to_string()),
}),
Json(format!(
"Repository pulled successfully for branch '{}'.",
branch
)),
))
}
Err(err) => {
Expand All @@ -264,21 +220,12 @@ pub async fn pull_handler(
/// Handler for fetching the current branch of the repository.
pub async fn get_current_branch_handler(
State(state): State<AppState>,
) -> Result<(StatusCode, Json<ApiResponse<String>>), (StatusCode, String)> {
) -> Result<(StatusCode, Json<String>), (StatusCode, String)> {
// Use the git::Interface from AppState to get the current branch
match state.git.get_current_branch().await {
Ok(branch_name) => {
info!("Current branch is: {}", branch_name);

// Return the branch name in the response
Ok((
StatusCode::OK,
Json(ApiResponse {
status: "success".to_string(),
message: "Current branch fetched successfully.".to_string(),
data: Some(branch_name),
}),
))
Ok((StatusCode::OK, Json(branch_name)))
}
Err(err) => {
error!("Failed to get current branch: {}", err);
Expand All @@ -293,21 +240,12 @@ pub async fn get_current_branch_handler(
/// Handler for fetching the default branch of the repository.
pub async fn get_default_branch_handler(
State(state): State<AppState>,
) -> Result<(StatusCode, Json<ApiResponse<String>>), (StatusCode, String)> {
) -> Result<(StatusCode, Json<String>), (StatusCode, String)> {
// Use the `get_default_branch` method from the `Gh` struct in AppState
match state.gh_client.get_default_branch().await {
Ok(default_branch) => {
info!("Default branch is: {}", default_branch);

// Return the default branch name in the response
Ok((
StatusCode::OK,
Json(ApiResponse {
status: "success".to_string(),
message: "Default branch fetched successfully.".to_string(),
data: Some(default_branch),
}),
))
Ok((StatusCode::OK, Json(default_branch)))
}
Err(err) => {
error!("Failed to get default branch: {}", err);
Expand All @@ -323,18 +261,14 @@ pub async fn get_default_branch_handler(
pub async fn get_issues_handler(
State(state): State<AppState>,
Path(state_param): Path<String>,
) -> Result<(StatusCode, Json<ApiResponse<IssuesData>>), (StatusCode, String)> {
) -> Result<(StatusCode, Json<IssuesData>), (StatusCode, String)> {
let state_param = state_param.as_str();

// Fetch issues using the GitHub client
match state.gh_client.get_issues(Some(state_param), None).await {
Ok(issues) => {
info!("Issues fetched successfully.");
let response = ApiResponse {
status: "success".to_string(),
message: "Issues fetched successfully.".to_string(),
data: Some(IssuesData { issues }),
};
let response = IssuesData { issues };
Ok((StatusCode::OK, Json(response)))
}
Err(err) => {
Expand Down
21 changes: 20 additions & 1 deletion backend/src/handlers_prelude/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
use std::collections::HashMap;

use axum::response::{IntoResponse, Response};
use axum::{extract::State, http::HeaderMap};
use chrono::{DateTime, Utc};
mod repo_fs;
Expand All @@ -22,14 +23,32 @@ mod github_handlers;
pub use github_handlers::*;

use color_eyre::{
eyre::{Context, ContextCompat},
eyre::{self, Context, ContextCompat},
Report,
};
use reqwest::StatusCode;
use tracing::{debug, error, trace};

use crate::{db::User, perms::Permission, AppState};

pub struct ApiError(eyre::Error);

impl IntoResponse for ApiError {
fn into_response(self) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", self.0),
)
.into_response()
}
}

impl From<eyre::Error> for ApiError {
fn from(err: eyre::Error) -> Self {
Self(err)
}
}

/// Quick and dirty way to convert an eyre error to a (StatusCode, message) response, meant for use with `map_err`, so that errors can be propagated out of
/// axum handlers with `?`.
pub fn eyre_to_axum_err(e: Report) -> (StatusCode, String) {
Expand Down
23 changes: 9 additions & 14 deletions frontend/src/lib/components/topbar/BranchButton.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
* }
* }
*/
async function fetchExistingBranches(): Promise<Branch[]> {
async function fetchExistingBranches() {
const response = await fetch(`${apiAddress}/api/branches`, {
method: 'GET',
credentials: 'include',
Expand All @@ -67,23 +67,20 @@
}
const data = await response.json();
return (
data.data?.branches?.map((branch: string) => ({
name: branch.split(' (')[0],
isProtected: branch.includes('(protected)')
})) ?? []
);
const formattedBranches: Branch[] = data.branches.map((branch: string) => ({
name: branch.replace(' (protected)', ''),
isProtected: branch.includes('(protected)')
}));
allBranches.set(formattedBranches);
}
async function fetchDefaultBranch() {
const response = await fetch(`${apiAddress}/api/repos/default-branch`);
if (response.ok) {
const data = await response.json();
const defaultBranch = data.data;
// Set the default branch to the baseBranch store
baseBranch.set(defaultBranch);
baseBranch.set(data);
} else {
console.error('Failed to fetch default branch:', response.statusText);
}
Expand All @@ -95,8 +92,7 @@
if (response.ok) {
const data = await response.json();
const currentBranch = data.data;
branchName.set(currentBranch);
branchName.set(data);
} else {
console.error('Failed to fetch current branch:', response.statusText);
}
Expand All @@ -108,8 +104,7 @@
onMount(async () => {
fetchDefaultBranch();
fetchCurrentBranch();
const branches = await fetchExistingBranches();
allBranches.set(branches);
await fetchExistingBranches();
});
async function setBranchName(input: string) {
Expand Down
Loading

0 comments on commit 178e3f6

Please sign in to comment.