This repository has been archived on 2022-09-04. You can view files and clone it, but cannot push or open issues or pull requests.
api/graphql/delivery/http/handler.go

65 lines
1.7 KiB
Go
Raw Normal View History

2020-06-02 15:45:21 +00:00
package httpdelivery
import (
"fmt"
2020-06-12 16:26:48 +00:00
"time"
2020-06-02 15:45:21 +00:00
"github.com/99designs/gqlgen/graphql/handler"
2020-06-03 15:21:28 +00:00
"github.com/99designs/gqlgen/graphql/handler/extension"
"github.com/99designs/gqlgen/graphql/handler/lru"
"github.com/99designs/gqlgen/graphql/handler/transport"
2020-06-02 15:45:21 +00:00
"github.com/99designs/gqlgen/graphql/playground"
"github.com/gin-gonic/gin"
"github.com/tribalwarshelp/api/graphql/generated"
"github.com/tribalwarshelp/api/graphql/resolvers"
)
2020-06-12 16:26:48 +00:00
const (
playgroundTTL = time.Hour / time.Second
)
2020-06-03 15:21:28 +00:00
type Config struct {
RouterGroup *gin.RouterGroup
Resolver *resolvers.Resolver
}
func Attach(cfg Config) error {
if cfg.Resolver == nil {
2020-06-02 15:45:21 +00:00
return fmt.Errorf("Graphql resolver cannot be nil")
}
2020-06-12 16:26:48 +00:00
gqlHandler := graphqlHandler(cfg.Resolver)
cfg.RouterGroup.GET("/graphql", gqlHandler)
cfg.RouterGroup.POST("/graphql", gqlHandler)
2020-06-03 15:21:28 +00:00
cfg.RouterGroup.GET("/", playgroundHandler())
2020-06-02 15:45:21 +00:00
return nil
}
// Defining the Graphql handler
func graphqlHandler(r *resolvers.Resolver) gin.HandlerFunc {
cfg := generated.Config{Resolvers: r}
2020-06-03 15:21:28 +00:00
srv := handler.New(generated.NewExecutableSchema(cfg))
srv.AddTransport(transport.GET{})
srv.AddTransport(transport.POST{})
srv.AddTransport(transport.MultipartForm{})
srv.Use(extension.Introspection{})
srv.Use(extension.AutomaticPersistedQuery{
Cache: lru.New(100),
})
2020-06-02 15:45:21 +00:00
return func(c *gin.Context) {
c.Header("Cache-Control", "no-store, must-revalidate")
2020-06-03 15:21:28 +00:00
srv.ServeHTTP(c.Writer, c.Request)
2020-06-02 15:45:21 +00:00
}
}
// Defining the Playground handler
func playgroundHandler() gin.HandlerFunc {
h := playground.Handler("Playground", "/graphql")
return func(c *gin.Context) {
2020-06-12 16:26:48 +00:00
c.Header("Cache-Control", fmt.Sprintf(`public, must-revalidate, max-age=%d, s-maxage=%d`, playgroundTTL, playgroundTTL))
2020-06-02 15:45:21 +00:00
h.ServeHTTP(c.Writer, c.Request)
}
}