GraphiQL

GraphiQL 是一个图形化的交互式浏览器 GraphQL IDE。 它在开发人员中非常受欢迎,因为它使探索和交互式开发 GraphQL API 变得容易。 在开发过程中,一个标准的 GraphiQL 集成通常足以帮助开发人员处理 API。 在生产环境中,应用程序可能需要自定义 GraphiQL 构建,其中包含公司徽标或特定的身份验证支持。

Spring for GraphQL 附带 一个标准的 GraphiQL index.html 页面,该页面使用 unpkg.com CDN 上托管的静态资源。 Spring Boot 应用程序可以轻松地 使用配置属性启用此页面

如果您的应用程序需要不依赖 CDN 的设置,或者您希望自定义用户界面,则可能需要自定义 GraphiQL 构建。 这可以通过两个步骤完成

  1. 配置并编译 GraphiQL 构建

  2. 通过 Spring Web 基础设施公开构建的 GraphiQL 实例

创建自定义 GraphiQL 构建

这部分通常不在此文档的范围内,因为自定义构建有多种选择。 您可以在 官方 GraphiQL 文档中找到更多信息。 您可以选择直接将构建结果复制到您的应用程序资源中。 或者,您可以通过利用 Node.js GradleMaven 构建插件,将 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 公开此新路由

您可能还需要配置您的应用程序以 提供相关的静态资源