Skip to content

Commit 178e3f6

Browse files
authored
This should actually be removing ApiResponse (#354)
1 parent a4c4407 commit 178e3f6

File tree

4 files changed

+62
-132
lines changed

4 files changed

+62
-132
lines changed

backend/src/handlers_prelude/github_handlers.rs

Lines changed: 22 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::handlers_prelude::eyre_to_axum_err;
1+
use crate::handlers_prelude::ApiError;
22
use crate::AppState;
33
use axum::routing::{get, post, put};
44
use axum::{
@@ -11,20 +11,6 @@ use serde::{Deserialize, Serialize};
1111
use serde_json::Value;
1212
use tracing::{error, info};
1313

14-
/// General API response structure
15-
#[derive(Serialize, Debug)]
16-
pub struct ApiResponse<T> {
17-
pub status: String,
18-
pub message: String,
19-
pub data: Option<T>,
20-
}
21-
22-
/// Error response structure
23-
#[derive(Serialize, Debug)]
24-
pub struct ApiErrorResponse {
25-
pub error: String,
26-
}
27-
2814
/// Represents the structure for a pull request creation response
2915
#[derive(Serialize, Debug)]
3016
pub struct CreatePRData {
@@ -72,13 +58,9 @@ pub struct UpdatePRRequest {
7258
/// Fetches the list of branches from a GitHub repository.
7359
pub async fn list_branches_handler(
7460
State(state): State<AppState>,
75-
) -> Result<(StatusCode, Json<ApiResponse<BranchesData>>), (StatusCode, String)> {
61+
) -> Result<Json<BranchesData>, ApiError> {
7662
// Fetch the branch details from GitHub using the GitHubClient instance
77-
let branch_details = state
78-
.gh_client
79-
.list_branches()
80-
.await
81-
.map_err(eyre_to_axum_err)?;
63+
let branch_details = state.gh_client.list_branches().await?;
8264

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

96-
// Return success response
78+
// Wrap the branches data in the BranchesData struct and return as JSON
9779
info!("Branches fetched successfully.");
98-
Ok((
99-
StatusCode::OK,
100-
Json(ApiResponse {
101-
status: "success".to_string(),
102-
message: "Branches fetched successfully".to_string(),
103-
data: Some(BranchesData { branches }),
104-
}),
105-
))
80+
Ok(Json(BranchesData { branches }))
10681
}
10782

10883
/// Handler to create a pull request from a specified head branch to a base branch.
10984
pub async fn create_pull_request_handler(
11085
State(state): State<AppState>,
11186
Json(payload): Json<CreatePRRequest>,
112-
) -> Result<(StatusCode, Json<ApiResponse<CreatePRData>>), (StatusCode, String)> {
87+
) -> Result<(StatusCode, Json<CreatePRData>), (StatusCode, String)> {
11388
// Create the pull request using the new method from GitHubClient
11489
match state
11590
.gh_client
@@ -128,14 +103,7 @@ pub async fn create_pull_request_handler(
128103
"Pull request created successfully from {} to {}",
129104
payload.head_branch, payload.base_branch
130105
);
131-
Ok((
132-
StatusCode::CREATED,
133-
Json(ApiResponse {
134-
status: "success".to_string(),
135-
message: "Pull request created successfully".to_string(),
136-
data: Some(CreatePRData { pull_request_url }),
137-
}),
138-
))
106+
Ok((StatusCode::CREATED, Json(CreatePRData { pull_request_url })))
139107
}
140108
Err(err) => {
141109
// Handle error case in creating the pull request
@@ -149,7 +117,7 @@ pub async fn create_pull_request_handler(
149117
pub async fn update_pull_request_handler(
150118
State(state): State<AppState>,
151119
Json(payload): Json<UpdatePRRequest>,
152-
) -> Result<(StatusCode, Json<ApiResponse<String>>), (StatusCode, String)> {
120+
) -> Result<(StatusCode, Json<String>), (StatusCode, String)> {
153121
// Update the pull request
154122
match state
155123
.gh_client
@@ -164,14 +132,7 @@ pub async fn update_pull_request_handler(
164132
{
165133
Ok(updated_pr_url) => {
166134
info!("Pull request #{} updated successfully", payload.pr_number);
167-
Ok((
168-
StatusCode::OK,
169-
Json(ApiResponse {
170-
status: "success".to_string(),
171-
message: "Pull request updated successfully.".to_string(),
172-
data: Some(updated_pr_url),
173-
}),
174-
))
135+
Ok((StatusCode::OK, Json(updated_pr_url)))
175136
}
176137
Err(err) => {
177138
let error_message = format!("Failed to update pull request: {:?}", err);
@@ -184,18 +145,14 @@ pub async fn update_pull_request_handler(
184145
pub async fn close_pull_request_handler(
185146
State(state): State<AppState>,
186147
Path(pr_number): Path<u64>,
187-
) -> Result<(StatusCode, Json<ApiResponse<String>>), (StatusCode, String)> {
148+
) -> Result<(StatusCode, Json<String>), (StatusCode, String)> {
188149
// Attempt to close the pull request
189150
match state.gh_client.close_pull_request(pr_number).await {
190151
Ok(_) => {
191152
info!("Pull request #{} closed successfully", pr_number);
192153
Ok((
193154
StatusCode::OK,
194-
Json(ApiResponse {
195-
status: "success".to_string(),
196-
message: "Pull request closed successfully.".to_string(),
197-
data: Some(format!("Pull request #{} closed.", pr_number)),
198-
}),
155+
Json(format!("Pull request #{} closed.", pr_number)),
199156
))
200157
}
201158
Err(err) => {
@@ -234,18 +191,17 @@ pub async fn checkout_or_create_branch_handler(
234191
pub async fn pull_handler(
235192
State(state): State<AppState>,
236193
Path(branch): Path<String>,
237-
) -> Result<(StatusCode, Json<ApiResponse<String>>), (StatusCode, String)> {
194+
) -> Result<(StatusCode, Json<String>), (StatusCode, String)> {
238195
// Attempt to pull the latest changes for the specified branch
239196
match state.git.git_pull_branch(&branch) {
240197
Ok(_) => {
241198
info!("Repository pulled successfully for branch '{}'.", branch);
242199
Ok((
243200
StatusCode::OK,
244-
Json(ApiResponse {
245-
status: "success".to_string(),
246-
message: format!("Repository pulled successfully for branch '{}'.", branch),
247-
data: Some("Pull operation completed.".to_string()),
248-
}),
201+
Json(format!(
202+
"Repository pulled successfully for branch '{}'.",
203+
branch
204+
)),
249205
))
250206
}
251207
Err(err) => {
@@ -264,21 +220,12 @@ pub async fn pull_handler(
264220
/// Handler for fetching the current branch of the repository.
265221
pub async fn get_current_branch_handler(
266222
State(state): State<AppState>,
267-
) -> Result<(StatusCode, Json<ApiResponse<String>>), (StatusCode, String)> {
223+
) -> Result<(StatusCode, Json<String>), (StatusCode, String)> {
268224
// Use the git::Interface from AppState to get the current branch
269225
match state.git.get_current_branch().await {
270226
Ok(branch_name) => {
271227
info!("Current branch is: {}", branch_name);
272-
273-
// Return the branch name in the response
274-
Ok((
275-
StatusCode::OK,
276-
Json(ApiResponse {
277-
status: "success".to_string(),
278-
message: "Current branch fetched successfully.".to_string(),
279-
data: Some(branch_name),
280-
}),
281-
))
228+
Ok((StatusCode::OK, Json(branch_name)))
282229
}
283230
Err(err) => {
284231
error!("Failed to get current branch: {}", err);
@@ -293,21 +240,12 @@ pub async fn get_current_branch_handler(
293240
/// Handler for fetching the default branch of the repository.
294241
pub async fn get_default_branch_handler(
295242
State(state): State<AppState>,
296-
) -> Result<(StatusCode, Json<ApiResponse<String>>), (StatusCode, String)> {
243+
) -> Result<(StatusCode, Json<String>), (StatusCode, String)> {
297244
// Use the `get_default_branch` method from the `Gh` struct in AppState
298245
match state.gh_client.get_default_branch().await {
299246
Ok(default_branch) => {
300247
info!("Default branch is: {}", default_branch);
301-
302-
// Return the default branch name in the response
303-
Ok((
304-
StatusCode::OK,
305-
Json(ApiResponse {
306-
status: "success".to_string(),
307-
message: "Default branch fetched successfully.".to_string(),
308-
data: Some(default_branch),
309-
}),
310-
))
248+
Ok((StatusCode::OK, Json(default_branch)))
311249
}
312250
Err(err) => {
313251
error!("Failed to get default branch: {}", err);
@@ -323,18 +261,14 @@ pub async fn get_default_branch_handler(
323261
pub async fn get_issues_handler(
324262
State(state): State<AppState>,
325263
Path(state_param): Path<String>,
326-
) -> Result<(StatusCode, Json<ApiResponse<IssuesData>>), (StatusCode, String)> {
264+
) -> Result<(StatusCode, Json<IssuesData>), (StatusCode, String)> {
327265
let state_param = state_param.as_str();
328266

329267
// Fetch issues using the GitHub client
330268
match state.gh_client.get_issues(Some(state_param), None).await {
331269
Ok(issues) => {
332270
info!("Issues fetched successfully.");
333-
let response = ApiResponse {
334-
status: "success".to_string(),
335-
message: "Issues fetched successfully.".to_string(),
336-
data: Some(IssuesData { issues }),
337-
};
271+
let response = IssuesData { issues };
338272
Ok((StatusCode::OK, Json(response)))
339273
}
340274
Err(err) => {

backend/src/handlers_prelude/mod.rs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
use std::collections::HashMap;
44

5+
use axum::response::{IntoResponse, Response};
56
use axum::{extract::State, http::HeaderMap};
67
use chrono::{DateTime, Utc};
78
mod repo_fs;
@@ -22,14 +23,32 @@ mod github_handlers;
2223
pub use github_handlers::*;
2324

2425
use color_eyre::{
25-
eyre::{Context, ContextCompat},
26+
eyre::{self, Context, ContextCompat},
2627
Report,
2728
};
2829
use reqwest::StatusCode;
2930
use tracing::{debug, error, trace};
3031

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

34+
pub struct ApiError(eyre::Error);
35+
36+
impl IntoResponse for ApiError {
37+
fn into_response(self) -> Response {
38+
(
39+
StatusCode::INTERNAL_SERVER_ERROR,
40+
format!("Something went wrong: {}", self.0),
41+
)
42+
.into_response()
43+
}
44+
}
45+
46+
impl From<eyre::Error> for ApiError {
47+
fn from(err: eyre::Error) -> Self {
48+
Self(err)
49+
}
50+
}
51+
3352
/// 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
3453
/// axum handlers with `?`.
3554
pub fn eyre_to_axum_err(e: Report) -> (StatusCode, String) {

frontend/src/lib/components/topbar/BranchButton.svelte

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
* }
4747
* }
4848
*/
49-
async function fetchExistingBranches(): Promise<Branch[]> {
49+
async function fetchExistingBranches() {
5050
const response = await fetch(`${apiAddress}/api/branches`, {
5151
method: 'GET',
5252
credentials: 'include',
@@ -67,23 +67,20 @@
6767
}
6868
6969
const data = await response.json();
70-
return (
71-
data.data?.branches?.map((branch: string) => ({
72-
name: branch.split(' (')[0],
73-
isProtected: branch.includes('(protected)')
74-
})) ?? []
75-
);
70+
const formattedBranches: Branch[] = data.branches.map((branch: string) => ({
71+
name: branch.replace(' (protected)', ''),
72+
isProtected: branch.includes('(protected)')
73+
}));
74+
allBranches.set(formattedBranches);
7675
}
7776
7877
async function fetchDefaultBranch() {
7978
const response = await fetch(`${apiAddress}/api/repos/default-branch`);
8079
8180
if (response.ok) {
8281
const data = await response.json();
83-
const defaultBranch = data.data;
84-
8582
// Set the default branch to the baseBranch store
86-
baseBranch.set(defaultBranch);
83+
baseBranch.set(data);
8784
} else {
8885
console.error('Failed to fetch default branch:', response.statusText);
8986
}
@@ -95,8 +92,7 @@
9592
9693
if (response.ok) {
9794
const data = await response.json();
98-
const currentBranch = data.data;
99-
branchName.set(currentBranch);
95+
branchName.set(data);
10096
} else {
10197
console.error('Failed to fetch current branch:', response.statusText);
10298
}
@@ -108,8 +104,7 @@
108104
onMount(async () => {
109105
fetchDefaultBranch();
110106
fetchCurrentBranch();
111-
const branches = await fetchExistingBranches();
112-
allBranches.set(branches);
107+
await fetchExistingBranches();
113108
});
114109
115110
async function setBranchName(input: string) {

0 commit comments

Comments
 (0)