aboutsummaryrefslogtreecommitdiff
path: root/src/api/helpers.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/api/helpers.rs')
-rw-r--r--src/api/helpers.rs24
1 files changed, 19 insertions, 5 deletions
diff --git a/src/api/helpers.rs b/src/api/helpers.rs
index 541b2def..57aa1ea1 100644
--- a/src/api/helpers.rs
+++ b/src/api/helpers.rs
@@ -1,8 +1,10 @@
use http_body_util::{BodyExt, Full as FullBody};
-use hyper::{body::Incoming as IncomingBody, Request, Response};
+use hyper::{body::Body, Request, Response};
use idna::domain_to_unicode;
use serde::{Deserialize, Serialize};
+use garage_util::error::Error as GarageError;
+
use crate::common_error::{CommonError as Error, *};
/// What kind of authorization is required to perform a given action
@@ -141,6 +143,7 @@ pub fn key_after_prefix(pfx: &str) -> Option<String> {
// =============== body helpers =================
+pub type EmptyBody = http_body_util::Empty<bytes::Bytes>;
pub type BytesBody = FullBody<bytes::Bytes>;
pub type BoxBody<E> = http_body_util::combinators::BoxBody<bytes::Bytes, E>;
@@ -153,22 +156,33 @@ pub fn bytes_body<E>(b: bytes::Bytes) -> BoxBody<E> {
pub fn empty_body<E>() -> BoxBody<E> {
BoxBody::new(http_body_util::Empty::new().map_err(|_| unreachable!()))
}
+pub fn string_bytes_body(s: String) -> BytesBody {
+ BytesBody::from(bytes::Bytes::from(s.into_bytes()))
+}
-pub async fn parse_json_body<T>(req: Request<IncomingBody>) -> Result<T, Error>
+pub async fn parse_json_body<T, B, E>(req: Request<B>) -> Result<T, E>
where
T: for<'de> Deserialize<'de>,
+ B: Body,
+ E: From<<B as Body>::Error> + From<Error>,
{
let body = req.into_body().collect().await?.to_bytes();
let resp: T = serde_json::from_slice(&body).ok_or_bad_request("Invalid JSON")?;
Ok(resp)
}
-pub fn json_ok_response<E, T: Serialize>(res: &T) -> Result<Response<BoxBody<E>>, Error> {
- let resp_json = serde_json::to_string_pretty(res).map_err(garage_util::error::Error::from)?;
+pub fn json_ok_response<E, T: Serialize>(res: &T) -> Result<Response<BoxBody<E>>, E>
+where
+ E: From<Error>,
+{
+ let resp_json = serde_json::to_string_pretty(res)
+ .map_err(GarageError::from)
+ .map_err(Error::from)?;
Ok(Response::builder()
.status(hyper::StatusCode::OK)
.header(http::header::CONTENT_TYPE, "application/json")
- .body(string_body(resp_json))?)
+ .body(string_body(resp_json))
+ .unwrap())
}
pub fn is_default<T: Default + PartialEq>(v: &T) -> bool {