1package graphql
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "strings"
9
10 "github.com/99designs/gqlgen/graphql"
11
12 "github.com/git-bug/git-bug/util/colors"
13)
14
15// adapted from https://github.com/99designs/gqlgen/blob/master/graphql/handler/debug/tracer.go
16
17type Tracer struct {
18 Out io.Writer
19}
20
21var _ interface {
22 graphql.HandlerExtension
23 graphql.ResponseInterceptor
24} = &Tracer{}
25
26func (a Tracer) ExtensionName() string {
27 return "error tracer"
28}
29
30func (a *Tracer) Validate(schema graphql.ExecutableSchema) error {
31 return nil
32}
33
34func stringify(value interface{}) string {
35 valueJson, err := json.MarshalIndent(value, " ", " ")
36 if err == nil {
37 return string(valueJson)
38 }
39
40 return fmt.Sprint(value)
41}
42
43func (a Tracer) InterceptResponse(ctx context.Context, next graphql.ResponseHandler) *graphql.Response {
44 resp := next(ctx)
45
46 if len(resp.Errors) == 0 {
47 return resp
48 }
49
50 rctx := graphql.GetOperationContext(ctx)
51
52 _, _ = fmt.Fprintln(a.Out, "GraphQL Request {")
53 for _, line := range strings.Split(rctx.RawQuery, "\n") {
54 _, _ = fmt.Fprintln(a.Out, " ", colors.Cyan(line))
55 }
56 for name, value := range rctx.Variables {
57 _, _ = fmt.Fprintf(a.Out, " var %s = %s\n", name, colors.Yellow(stringify(value)))
58 }
59
60 _, _ = fmt.Fprintln(a.Out, " resp:", colors.Green(stringify(resp)))
61 for _, err := range resp.Errors {
62 _, _ = fmt.Fprintln(a.Out, " error:", colors.Bold(err.Path.String()+":"), colors.Red(err.Message))
63 }
64 _, _ = fmt.Fprintln(a.Out, "}")
65 _, _ = fmt.Fprintln(a.Out)
66 return resp
67}