此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring GraphQL 1.3.4spring-doc.cadn.net.cn

图形 QL

GraphiQL 是一个图形化、交互式的浏览器内 GraphQL IDE。 它在开发人员中非常受欢迎,因为它使探索和交互式开发 GraphQL API 变得容易。 在开发过程中,现有的 GraphiQL 集成通常足以帮助开发人员使用 API。 在生产中,应用程序可能需要自定义 GraphiQL 版本,该版本附带公司徽标或特定的身份验证支持。spring-doc.cadn.net.cn

Spring for GraphQL 附带一个库存的 GraphiQLindex.html使用托管在 unpkg.com CDN 上的静态资源。 Spring Boot 应用程序可以使用 configuration 属性轻松启用此页面spring-doc.cadn.net.cn

如果您的应用程序需要不依赖于 CDN 的设置,或者您希望自定义用户界面,则可能需要自定义 GraphiQL 版本。 这可以通过两个步骤完成:spring-doc.cadn.net.cn

  1. 配置和编译 GraphiQL 内部版本spring-doc.cadn.net.cn

  2. 通过 Spring Web 基础设施公开构建的 GraphiQL 实例spring-doc.cadn.net.cn

创建自定义 GraphiQL 内部版本

这部分通常不在本文档的范围之内,因为自定义构建有多种选择。 您可以在 GraphiQL 官方文档中找到更多信息。 您可以选择直接在应用程序资源中复制构建结果。 或者,您也可以利用 GradleMaven 构建插件将 JavaScript 构建作为单独的模块集成到项目中Node.js。spring-doc.cadn.net.cn

公开 GraphiQL 实例

一旦 GraphiQL 构建在类路径上可用,您就可以将其作为功能性 Web 框架的端点公开。spring-doc.cadn.net.cn

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 Load the GraphiQL page from the classpath (here, we are using the version shipped with Spring for GraphQL)
2 Configure a web handler for processing HTTP requests; you can implement a custom HandlerFunction depending on your use case
3 Finally, map the handler to a specific HTTP endpoint
4 Expose this new route through a RouterFunction bean

You might also need to configure your application to serve the relevant static resources.spring-doc.cadn.net.cn