...
1 package debug
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "os"
9 "strings"
10
11 . "github.com/logrusorgru/aurora/v3"
12 "github.com/mattn/go-colorable"
13 "github.com/mattn/go-isatty"
14
15 "github.com/99designs/gqlgen/graphql"
16 )
17
18 type Tracer struct {
19 DisableColor bool
20 au Aurora
21 out io.Writer
22 }
23
24 var _ interface {
25 graphql.HandlerExtension
26 graphql.ResponseInterceptor
27 } = &Tracer{}
28
29 func (a Tracer) ExtensionName() string {
30 return "ApolloTracing"
31 }
32
33 func (a *Tracer) Validate(schema graphql.ExecutableSchema) error {
34 isTTY := isatty.IsTerminal(os.Stdout.Fd())
35
36 a.au = NewAurora(!a.DisableColor && isTTY)
37 a.out = colorable.NewColorableStdout()
38
39 return nil
40 }
41
42 func stringify(value interface{}) string {
43 valueJson, err := json.MarshalIndent(value, " ", " ")
44 if err == nil {
45 return string(valueJson)
46 }
47
48 return fmt.Sprint(value)
49 }
50
51 func (a Tracer) InterceptResponse(ctx context.Context, next graphql.ResponseHandler) *graphql.Response {
52 rctx := graphql.GetOperationContext(ctx)
53
54 fmt.Fprintln(a.out, "GraphQL Request {")
55 for _, line := range strings.Split(rctx.RawQuery, "\n") {
56 fmt.Fprintln(a.out, " ", Cyan(line))
57 }
58 for name, value := range rctx.Variables {
59 fmt.Fprintf(a.out, " var %s = %s\n", name, Yellow(stringify(value)))
60 }
61 resp := next(ctx)
62
63 fmt.Fprintln(a.out, " resp:", Green(stringify(resp)))
64 for _, err := range resp.Errors {
65 fmt.Fprintln(a.out, " error:", Bold(err.Path.String()+":"), Red(err.Message))
66 }
67 fmt.Fprintln(a.out, "}")
68 fmt.Fprintln(a.out)
69 return resp
70 }
71
View as plain text