sui_graphql_rpc/server/
graphiql_server.rs

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