Skip to content

Commit

Permalink
refactor(torii): add accept header extractor
Browse files Browse the repository at this point in the history
Signed-off-by: Shanin Roman <[email protected]>
  • Loading branch information
Erigara committed Jul 2, 2024
1 parent 6910e37 commit ea2fc50
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 9 deletions.
12 changes: 5 additions & 7 deletions torii/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ use tower_http::{
trace::{DefaultMakeSpan, TraceLayer},
};
use utils::{
body::{ClientQueryRequestExtractor, ScaleVersioned},
extractors::{ClientQueryRequestExtractor, ExtractAccept, ScaleVersioned},
Scale,
};

Expand Down Expand Up @@ -118,11 +118,10 @@ impl Torii {
&format!("{}/*tail", uri::STATUS),
get({
let metrics_reporter = self.metrics_reporter.clone();
move |headers: axum::http::header::HeaderMap, axum::extract::Path(tail): axum::extract::Path<String>| {
let accept = headers.get(axum::http::header::ACCEPT);
move |accept: Option<ExtractAccept>, axum::extract::Path(tail): axum::extract::Path<String>| {
core::future::ready(routing::handle_status(
&metrics_reporter,
accept,
accept.map(|extract| extract.0),
Some(&tail),
))
}
Expand All @@ -132,9 +131,8 @@ impl Torii {
uri::STATUS,
get({
let metrics_reporter = self.metrics_reporter.clone();
move |headers: axum::http::header::HeaderMap| {
let accept = headers.get(axum::http::header::ACCEPT);
core::future::ready(routing::handle_status(&metrics_reporter, accept, None))
move |accept: Option<ExtractAccept>| {
core::future::ready(routing::handle_status(&metrics_reporter, accept.map(|extract| extract.0), None))
}
}),
)
Expand Down
28 changes: 26 additions & 2 deletions torii/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ impl<T: Encode + Send> IntoResponse for Scale<T> {
}
}

pub mod body {
pub mod extractors {
use axum::{
async_trait,
body::Bytes,
extract::{FromRequest, FromRequestParts, Query, Request},
http::StatusCode,
};
use iroha_data_model::query::cursor::ForwardCursor;

Expand Down Expand Up @@ -57,7 +58,7 @@ pub mod body {
.map_err(|err| {
(
axum::http::StatusCode::BAD_REQUEST,
format!("Transaction Rejected (Malformed), Reason : '{err}'"),
format!("Could not decode request: {err}"),
)
.into_response()
})
Expand Down Expand Up @@ -93,4 +94,27 @@ pub mod body {
.map(ClientQueryRequestExtractor)
}
}

/// Extractor of Accept header
pub struct ExtractAccept(pub HeaderValue);

#[async_trait]
impl<S> FromRequestParts<S> for ExtractAccept
where
S: Send + Sync,
{
type Rejection = (StatusCode, &'static str);

async fn from_request_parts(
parts: &mut axum::http::request::Parts,
_state: &S,
) -> Result<Self, Self::Rejection> {
parts
.headers
.get(axum::http::header::ACCEPT)
.cloned()
.map(ExtractAccept)
.ok_or((StatusCode::BAD_REQUEST, "`Accept` header is missing"))
}
}
}

0 comments on commit ea2fc50

Please sign in to comment.