blob: 0d345bbf0770566decd0486f3e3c2e233039f5b0 [file] [log] [blame]
giolekvac76b21b2020-04-18 19:28:43 +04001package schema
2
3import (
4 "bytes"
5 "fmt"
6 "io/ioutil"
7 "net/http"
8 "strings"
9
10 "github.com/golang/glog"
11 "github.com/itaysk/regogo"
12 "github.com/vektah/gqlparser/ast"
13 "github.com/vektah/gqlparser/parser"
14)
15
16const jsonContentType = "application/json"
17
18const getSchemaQuery = `{ "query": "{ getGQLSchema() { schema } }" }`
19
20const addSchemaQuery = `{
21 "query": "mutation { updateGQLSchema(input: {set: {schema: \"%s\"}}) { gqlSchema { id schema } } }" }`
22
23type DgraphSchemaStore struct {
24 dgraphAddress string
25 gqlSchema string
26 schema *ast.SchemaDocument
27}
28
29func NewDgraphSchemaStore(dgraphAddress string) (SchemaStore, error) {
30 ret := &DgraphSchemaStore{dgraphAddress: dgraphAddress, gqlSchema: ""}
31 if err := ret.fetchSchema(); err != nil {
32 return nil, err
33 }
34 return ret, nil
35}
36
37func (s *DgraphSchemaStore) Schema() *ast.SchemaDocument {
38 return s.schema
39}
40
41func (s *DgraphSchemaStore) AddSchema(gqlSchema string) error {
42 return s.SetSchema(s.gqlSchema + gqlSchema)
43}
44
45func (s *DgraphSchemaStore) SetSchema(gqlSchema string) error {
46 glog.Info("Setting GraphQL schema:")
47 glog.Info(gqlSchema)
48 req := fmt.Sprintf(addSchemaQuery, strings.ReplaceAll(strings.ReplaceAll(gqlSchema, "\n", " "), "\t", " "))
49 resp, err := http.Post(s.dgraphAddress, jsonContentType, bytes.NewReader([]byte(req)))
giolekvac76b21b2020-04-18 19:28:43 +040050 if err != nil {
51 return err
52 }
giolekvacba39b82020-04-18 20:56:05 +040053 glog.Infof("Response status code: %d", resp.StatusCode)
giolekvac76b21b2020-04-18 19:28:43 +040054 respBody, err := ioutil.ReadAll(resp.Body)
55 if err != nil {
56 return err
57 }
58 glog.Infof("Result: %s", string(respBody))
59 s.gqlSchema = gqlSchema
60 return s.fetchSchema()
61}
62
63func (s *DgraphSchemaStore) fetchSchema() error {
64 glog.Infof("Getting GraphQL schema with query: %s", getSchemaQuery)
65 resp, err := http.Post(s.dgraphAddress, jsonContentType, bytes.NewReader([]byte(getSchemaQuery)))
66 if err != nil {
67 return err
68 }
69 glog.Infof("Response status code: %d", resp.StatusCode)
70 respBody, err := ioutil.ReadAll(resp.Body)
71 if err != nil {
72 return err
73 }
74 glog.Infof("Result: %s", string(respBody))
75 gqlSchema, err := regogo.Get(string(respBody), "input.data.getGQLSchema.schema")
76 if err != nil {
77 return err
78 }
79 schema, gqlErr := parser.ParseSchema(&ast.Source{Input: gqlSchema.String()})
80 if gqlErr != nil {
81 return gqlErr
82 }
83 s.schema = schema
84 return nil
85}