/
handler_graphql.go
73 lines (62 loc) · 1.77 KB
/
handler_graphql.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package transport
import (
"context"
"errors"
"net/http"
gographql "github.com/graphql-go/graphql"
"github.com/graphql-go/handler"
"github.com/authgear/authgear-server/pkg/admin/graphql"
"github.com/authgear/authgear-server/pkg/lib/infra/db/appdb"
"github.com/authgear/authgear-server/pkg/util/graphqlutil"
"github.com/authgear/authgear-server/pkg/util/httproute"
)
func ConfigureGraphQLRoute(route httproute.Route) []httproute.Route {
route = route.WithMethods("GET", "POST")
return []httproute.Route{
route.WithPathPattern("/graphql"),
route.WithPathPattern("/_api/admin/graphql"),
}
}
var errRollback = errors.New("rollback transaction")
type GraphQLHandler struct {
GraphQLContext *graphql.Context
AppDatabase *appdb.Handle
}
func (h *GraphQLHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
graphiql := &graphqlutil.GraphiQL{
Title: "GraphiQL: Admin API - Authgear",
}
graphiql.ServeHTTP(rw, r)
return
} else {
// graphql-go/handler will use "query=" when it is present.
// This causes GraphiQL unable to fetch the schema.
q := r.URL.Query()
q.Del("query")
r.URL.RawQuery = q.Encode()
}
err := h.AppDatabase.WithTx(func() error {
doRollback := false
graphqlHandler := handler.New(&handler.Config{
Schema: graphql.Schema,
Pretty: false,
GraphiQL: false,
Playground: false,
ResultCallbackFn: func(ctx context.Context, params *gographql.Params, result *gographql.Result, responseBody []byte) {
if result.HasErrors() {
doRollback = true
}
},
})
ctx := graphql.WithContext(r.Context(), h.GraphQLContext)
graphqlHandler.ContextHandler(ctx, rw, r)
if doRollback {
return errRollback
}
return nil
})
if err != nil && !errors.Is(err, errRollback) {
panic(err)
}
}