tako/
graphiql.rs

1//! GraphiQL HTML responder and helper for Tako.
2//!
3//! Enable with the `graphiql` feature. This module provides a `graphiql()` function that
4//! returns an HTML page rendering the GraphiQL UI, wired to your GraphQL and WS endpoints.
5#![cfg(feature = "graphiql")]
6#![cfg_attr(docsrs, doc(cfg(feature = "graphiql")))]
7
8use http::{HeaderValue, header};
9
10use crate::{body::TakoBody, responder::Responder, types::Response};
11
12/// Response wrapper for GraphiQL HTML.
13pub struct GraphiQL(pub(crate) String);
14
15impl Responder for GraphiQL {
16  fn into_response(self) -> Response {
17    let mut res = Response::new(TakoBody::from(self.0));
18    res.headers_mut().insert(
19      header::CONTENT_TYPE,
20      HeaderValue::from_static("text/html; charset=utf-8"),
21    );
22    res
23  }
24}
25
26/// Build a GraphiQL HTML response.
27///
28/// - `endpoint`: HTTP endpoint for GraphQL queries/mutations (e.g., "/graphql")
29/// - `subscription_endpoint`: optional WS URL for subscriptions (e.g., "ws://localhost:8080/ws")
30pub fn graphiql(endpoint: &str, subscription_endpoint: Option<&str>) -> GraphiQL {
31  let mut builder = async_graphql::http::GraphiQLSource::build().endpoint(endpoint);
32  if let Some(ws) = subscription_endpoint {
33    builder = builder.subscription_endpoint(ws);
34  }
35  GraphiQL(builder.finish())
36}