handler.go

 1package graphql
 2
 3import (
 4	"context"
 5	"net/http"
 6
 7	"github.com/MichaelMure/git-bug/cache"
 8	"github.com/MichaelMure/git-bug/repository"
 9	graphqlHandler "github.com/graphql-go/handler"
10)
11
12type Handler struct {
13	handler *graphqlHandler.Handler
14	cache   cache.Cache
15}
16
17func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
18	ctx := context.WithValue(r.Context(), "cache", h.cache)
19	h.handler.ContextHandler(ctx, w, r)
20}
21
22func NewHandler(repo repository.Repo) (*Handler, error) {
23	schema, err := graphqlSchema()
24
25	if err != nil {
26		return nil, err
27	}
28
29	h := graphqlHandler.New(&graphqlHandler.Config{
30		Schema:   &schema,
31		Pretty:   true,
32		GraphiQL: true,
33	})
34
35	c := cache.NewDefaultCache()
36	c.RegisterDefaultRepository(repo)
37
38	return &Handler{
39		handler: h,
40		cache:   c,
41	}, nil
42}