How to pass Axum ConnectInfo/Request into GraphQL endpoint? #1285
Unanswered
ehsanonline
asked this question in
Q&A
Replies: 1 comment 1 reply
-
hello! I had a similar need and I accomplished it that way. I've created middleware use axum::http::Request;
use axum::http::StatusCode;
use axum::middleware::Next;
use axum::response::Response;
#[derive(Debug, Clone)]
pub struct Headers(pub axum::http::HeaderMap);
impl Headers {
pub fn get(&self, key: &str) -> Option<&axum::http::HeaderValue> {
self.0.get(key)
}
}
pub async fn headers<T>(mut request: Request<T>, next: Next<T>) -> Result<Response, StatusCode> {
let headers = request.headers().clone();
request.extensions_mut().insert(Headers(headers));
Ok(next.run(request).await)
} and then call middleware before graphql handler ...
let router = Router::new()
.route(
"/api/graphql",
get(graphql_playground).post(graphql_handler),
)
.layer(
ServiceBuilder::new()
.layer(middleware::from_fn(headers))
.layer(middleware::from_fn(guard))
.layer(cors)
.layer(Extension(secret_store))
.layer(Extension(schema)),
);
... then in my handler I do that #[axum::debug_handler]
pub async fn graphql_handler(
schema: Extension<AppSchema>,
Extension(secret_store): Extension<SecretStore>,
Extension(token): Extension<Option<auth::ParsedToken>>,
Extension(headers): Extension<headers::Headers>,
req: GraphQLRequest,
) -> GraphQLResponse {
let execute = schema
.execute(
req.into_inner()
.data(token)
.data(secret_store)
.data(headers),
)
.await;
execute.into()
} hope my example would help you. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello. I'm using Axum and I like to get Axum request info into my GraphQL, for getting information's such as IP, raw request data and more... I implement This example But I got this error at Graphql's post endpoint (under
graphql_handler
):my endpooint:
I noticed when I remove
req: GraphQLRequest,
the error disappears. I think if I could pass that to endpoint, I will be able to inject it viaschema.execute(req.into_inner().data(info)).await
to my queries. Thanks.Beta Was this translation helpful? Give feedback.
All reactions