feat: proxy response bodies

This commit is contained in:
sam 2024-02-15 15:11:04 +01:00
parent 0858d4893a
commit 18b644d24b
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
4 changed files with 121 additions and 36 deletions

View file

@ -1,14 +1,15 @@
use std::sync::Arc;
use axum::{extract::OriginalUri, routing::post, Extension, Json, Router};
use axum::{extract::OriginalUri, http::StatusCode, routing::post, Extension, Json, Router};
use eyre::ContextCompat;
use foxchat::{
fed,
fed::{self, request::ResponseError},
http::ApiError,
model::{
http::{channel::CreateMessageParams, guild::CreateGuildParams},
Guild, Message,
},
FoxError,
};
use serde::{de::DeserializeOwned, Serialize};
use tracing::debug;
@ -45,9 +46,36 @@ async fn proxy_get<R: Serialize + DeserializeOwned>(
&format!("/_fox/chat/{}", proxy_path),
Some(user.id),
)
.await?;
.await;
Ok(Json(resp))
match resp {
Ok(r) => return Ok(Json(r)),
Err(e) => {
if let Some(e) = e.downcast_ref::<ResponseError>() {
match e {
ResponseError::JsonError => {
return Err(FoxError::ProxyInternalServerError.into())
}
ResponseError::NotOk {
status,
code,
message,
} => {
return Err(ApiError {
status: StatusCode::from_u16(status.to_owned()).map_err(
|_| -> ApiError { FoxError::ProxyInternalServerError.into() },
)?,
code: code.to_owned(),
message: message.to_owned(),
})
}
}
} else {
tracing::error!("proxying GET request: {}", e);
return Err(FoxError::ProxyInternalServerError.into());
}
}
}
}
async fn proxy_post<B: Serialize, R: Serialize + DeserializeOwned>(
@ -71,7 +99,34 @@ async fn proxy_post<B: Serialize, R: Serialize + DeserializeOwned>(
Some(user.id),
&body,
)
.await?;
.await;
Ok(Json(resp))
match resp {
Ok(r) => return Ok(Json(r)),
Err(e) => {
if let Some(e) = e.downcast_ref::<ResponseError>() {
match e {
ResponseError::JsonError => {
return Err(FoxError::ProxyInternalServerError.into())
}
ResponseError::NotOk {
status,
code,
message,
} => {
return Err(ApiError {
status: StatusCode::from_u16(status.to_owned()).map_err(
|_| -> ApiError { FoxError::ProxyInternalServerError.into() },
)?,
code: code.to_owned(),
message: message.to_owned(),
})
}
}
} else {
tracing::error!("proxying POST request: {}", e);
return Err(FoxError::ProxyInternalServerError.into());
}
}
}
}