aboutsummaryrefslogtreecommitdiffstats
path: root/api/graphql/tracer.go
blob: 11448a3ae7b845585aade85e6fee7cd09f6f961c (plain) (blame)
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
package graphql

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"strings"

	"github.com/99designs/gqlgen/graphql"

	"github.com/MichaelMure/git-bug/util/colors"
)

// adapted from https://github.com/99designs/gqlgen/blob/master/graphql/handler/debug/tracer.go

type Tracer struct {
	Out io.Writer
}

var _ interface {
	graphql.HandlerExtension
	graphql.ResponseInterceptor
} = &Tracer{}

func (a Tracer) ExtensionName() string {
	return "error tracer"
}

func (a *Tracer) Validate(schema graphql.ExecutableSchema) error {
	return nil
}

func stringify(value interface{}) string {
	valueJson, err := json.MarshalIndent(value, "  ", "  ")
	if err == nil {
		return string(valueJson)
	}

	return fmt.Sprint(value)
}

func (a Tracer) InterceptResponse(ctx context.Context, next graphql.ResponseHandler) *graphql.Response {
	resp := next(ctx)

	if len(resp.Errors) == 0 {
		return resp
	}

	rctx := graphql.GetOperationContext(ctx)

	_, _ = fmt.Fprintln(a.Out, "GraphQL Request {")
	for _, line := range strings.Split(rctx.RawQuery, "\n") {
		_, _ = fmt.Fprintln(a.Out, " ", colors.Cyan(line))
	}
	for name, value := range rctx.Variables {
		_, _ = fmt.Fprintf(a.Out, "  var %s = %s\n", name, colors.Yellow(stringify(value)))
	}

	_, _ = fmt.Fprintln(a.Out, "  resp:", colors.Green(stringify(resp)))
	for _, err := range resp.Errors {
		_, _ = fmt.Fprintln(a.Out, "  error:", colors.Bold(err.Path.String()+":"), colors.Red(err.Message))
	}
	_, _ = fmt.Fprintln(a.Out, "}")
	_, _ = fmt.Fprintln(a.Out)
	return resp
}