iota_graphql_rpc/server/
graphiql_server.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use axum::extract::Path;
6use tokio_util::sync::CancellationToken;
7use tracing::info;
8
9use crate::{
10    config::{ServerConfig, Version},
11    error::Error,
12    server::builder::ServerBuilder,
13};
14
15async fn graphiql(
16    ide_title: axum::Extension<Option<String>>,
17    path: Option<Path<String>>,
18) -> impl axum::response::IntoResponse {
19    let endpoint = if let Some(Path(path)) = path {
20        format!("/graphql/{}", path)
21    } else {
22        "/graphql".to_string()
23    };
24    let gq = async_graphql::http::GraphiQLSource::build().endpoint(&endpoint);
25    if let axum::Extension(Some(title)) = ide_title {
26        axum::response::Html(gq.title(&title).finish())
27    } else {
28        axum::response::Html(gq.finish())
29    }
30}
31
32pub async fn start_graphiql_server(
33    server_config: &ServerConfig,
34    version: &Version,
35    cancellation_token: CancellationToken,
36) -> Result<(), Error> {
37    info!("Starting server with config: {:#?}", server_config);
38    info!("Server version: {}", version);
39    start_graphiql_server_impl(
40        ServerBuilder::from_config(server_config, version, cancellation_token).await?,
41        server_config.ide.ide_title.clone(),
42    )
43    .await
44}
45
46async fn start_graphiql_server_impl(
47    server_builder: ServerBuilder,
48    ide_title: String,
49) -> Result<(), Error> {
50    let address = server_builder.address();
51
52    // Add GraphiQL IDE handler on GET request to `/`` endpoint
53    let server = server_builder
54        .route("/", axum::routing::get(graphiql))
55        .route("/:version", axum::routing::get(graphiql))
56        .route("/graphql", axum::routing::get(graphiql))
57        .route("/graphql/:version", axum::routing::get(graphiql))
58        .layer(axum::extract::Extension(Some(ide_title)))
59        .build()?;
60
61    info!("Launch GraphiQL IDE at: http://{}", address);
62
63    server.run().await
64}