api/graphql.go
Claude 43abce034e
chore(api): AX compliance sweep — banned imports, naming, test coverage
Replace fmt/errors/strings/encoding/json/os/os/exec/path/filepath with
core primitives; rename abbreviated variables; add Ugly test variants to
all test files; rename integration tests to TestFilename_Function_{Good,Bad,Ugly}.

Co-Authored-By: Virgil <virgil@lethean.io>
2026-03-31 09:27:41 +01:00

63 lines
1.8 KiB
Go

// SPDX-License-Identifier: EUPL-1.2
package api
import (
"net/http"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/gin-gonic/gin"
)
// defaultGraphQLPath is the URL path where the GraphQL endpoint is mounted.
const defaultGraphQLPath = "/graphql"
// graphqlConfig holds configuration for the GraphQL endpoint.
type graphqlConfig struct {
schema graphql.ExecutableSchema
path string
playground bool
}
// GraphQLOption configures a GraphQL endpoint.
type GraphQLOption func(*graphqlConfig)
// WithPlayground enables the GraphQL Playground UI at {path}/playground.
func WithPlayground() GraphQLOption {
return func(config *graphqlConfig) {
config.playground = true
}
}
// WithGraphQLPath sets a custom URL path for the GraphQL endpoint.
// The default path is "/graphql".
func WithGraphQLPath(path string) GraphQLOption {
return func(config *graphqlConfig) {
config.path = path
}
}
// mountGraphQL registers the GraphQL handler and optional playground on the Gin engine.
func mountGraphQL(router *gin.Engine, config *graphqlConfig) {
graphqlServer := handler.NewDefaultServer(config.schema)
graphqlHandler := gin.WrapH(graphqlServer)
// Mount the GraphQL endpoint for all HTTP methods (POST for queries/mutations,
// GET for playground redirects and introspection).
router.Any(config.path, graphqlHandler)
if config.playground {
playgroundPath := config.path + "/playground"
playgroundHandler := playground.Handler("GraphQL", config.path)
router.GET(playgroundPath, wrapHTTPHandler(playgroundHandler))
}
}
// wrapHTTPHandler adapts a standard http.Handler to a Gin handler function.
func wrapHTTPHandler(handler http.Handler) gin.HandlerFunc {
return func(c *gin.Context) {
handler.ServeHTTP(c.Writer, c.Request)
}
}