forked from graph-gophers/graphql-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgraphql.go
84 lines (71 loc) · 1.88 KB
/
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
74
75
76
77
78
79
80
81
82
83
84
package graphql
import (
"context"
"encoding/json"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/neelance/graphql-go/errors"
"github.com/neelance/graphql-go/internal/exec"
"github.com/neelance/graphql-go/internal/query"
"github.com/neelance/graphql-go/internal/schema"
)
type Schema struct {
schema *schema.Schema
exec *exec.Exec
}
func ParseSchema(schemaString string, resolver interface{}) (*Schema, error) {
s, err := schema.Parse(schemaString)
if err != nil {
return nil, err
}
e, err2 := exec.Make(s, resolver)
if err2 != nil {
return nil, err2
}
return &Schema{
schema: s,
exec: e,
}, nil
}
type Response struct {
Data interface{} `json:"data,omitempty"`
Errors []*errors.QueryError `json:"errors,omitempty"`
Extensions map[string]interface{} `json:"extensions,omitempty"`
}
func (s *Schema) Exec(ctx context.Context, queryString string, operationName string, variables map[string]interface{}) *Response {
document, err := query.Parse(queryString, s.schema.Resolve)
if err != nil {
return &Response{
Errors: []*errors.QueryError{err},
}
}
span, subCtx := opentracing.StartSpanFromContext(ctx, "GraphQL request")
span.SetTag("query", queryString)
if operationName != "" {
span.SetTag("operationName", operationName)
}
if len(variables) != 0 {
span.SetTag("variables", variables)
}
defer span.Finish()
data, errs := exec.ExecuteRequest(subCtx, s.exec, document, operationName, variables)
if len(errs) != 0 {
ext.Error.Set(span, true)
span.SetTag("errorMsg", errs)
}
return &Response{
Data: data,
Errors: errs,
}
}
func SchemaToJSON(schemaString string) ([]byte, error) {
s, err := schema.Parse(schemaString)
if err != nil {
return nil, err
}
result, err2 := exec.IntrospectSchema(s)
if err2 != nil {
return nil, err
}
return json.Marshal(result)
}