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 公開此新路由

您可能還需要配置您的應用程式以 提供相關的靜態資源