GraphiQL
GraphiQL 是一个图形化的交互式浏览器内 GraphQL IDE。它在开发者中非常流行,因为它使探索和交互式开发 GraphQL API 变得容易。在开发过程中,一个标准的 GraphiQL 集成通常足以帮助开发者进行 API 工作。在生产环境中,应用程序可能需要一个自定义的 GraphiQL 构建,其中包含公司标志或特定的身份验证支持。
Spring for GraphQL 附带一个标准的 GraphiQL index.html 页面,该页面使用托管在 esm.sh CDN 上的静态资源。Spring Boot 应用程序可以通过配置属性轻松启用此页面。
如果您的应用程序需要不依赖 CDN 的设置,或者您希望自定义用户界面,则可能需要自定义 GraphiQL 构建。这可以通过两个步骤完成:
-
配置并编译 GraphiQL 构建。
-
通过 Spring web 基础设施公开已构建的 GraphiQL 实例。
创建自定义 GraphiQL 构建
这部分通常不在本文档的范围之内,因为有几种自定义构建的选项。您可以在官方 GraphiQL 文档中找到更多信息。您可以选择将构建结果直接复制到应用程序资源中。或者,您可以通过利用 Node.js Gradle 或 Maven 构建插件,将 JavaScript 构建作为单独的模块集成到项目中。
暴露 GraphiQL 实例
一旦 GraphiQL 构建在类路径中可用,您就可以使用函数式 Web 框架将其作为端点公开。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.graphql.server.webmvc.GraphiQlHandler;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerResponse;
@Configuration
public class GraphiQlConfiguration {
@Bean
@Order(0)
public RouterFunction<ServerResponse> graphiQlRouterFunction() {
RouterFunctions.Builder builder = RouterFunctions.route();
ClassPathResource graphiQlPage = new ClassPathResource("graphiql/index.html"); (1)
GraphiQlHandler graphiQLHandler = new GraphiQlHandler("/graphql", "", graphiQlPage); (2)
builder = builder.GET("/graphiql", graphiQLHandler::handleRequest); (3)
return builder.build(); (4)
}
}
| 1 | 从类路径加载 GraphiQL 页面(这里我们使用的是 Spring for GraphQL 附带的版本)。 |
| 2 | 配置一个用于处理 HTTP 请求的 Web 处理程序;您可以根据您的用例实现自定义的 HandlerFunction。 |
| 3 | 最后,将处理程序映射到特定的 HTTP 端点。 |
| 4 | 通过 RouterFunction bean 公开此新路由。 |
您可能还需要配置您的应用程序以提供相关的静态资源。