-
Notifications
You must be signed in to change notification settings - Fork 47
/
handler.go
75 lines (63 loc) · 1.9 KB
/
handler.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
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT License was not distributed with this
// file, you can obtain one at https://opensource.org/licenses/MIT.
//
// Copyright (c) DUSK NETWORK. All rights reserved.
package gql
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/dusk-network/dusk-blockchain/pkg/core/database"
"github.com/go-chi/render"
"github.com/graphql-go/graphql"
)
type data struct {
Query string `json:"query"`
Operation string `json:"operationName,omitempty"`
Variables map[string]interface{} `json:"variables,omitempty"`
}
// handleQuery to process graphQL query.
func handleQuery(schema *graphql.Schema, w http.ResponseWriter, r *http.Request, db database.DB) {
if r.Body == nil {
http.Error(w, "Must provide graphql query in request body", 400)
return
}
// Read and close JSON request body
body, err := ioutil.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
msg := fmt.Sprintf("%d error request: %v", http.StatusBadRequest, err)
log.Error(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
var req data
if err := json.Unmarshal(body, &req); err != nil {
msg := fmt.Sprintf("Unmarshal request: %v", err)
log.Error(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
// Execute graphql query
result := graphql.Do(graphql.Params{
Schema: *schema,
RequestString: req.Query,
VariableValues: req.Variables,
OperationName: req.Operation,
Context: context.WithValue(context.Background(), "database", db), //nolint
})
//// Error check
//if len(result.Errors) > 0 {
// log.
// WithField("query", req.Query).
// WithField("variables", req.Variables).
// WithField("operation", req.Operation).
// WithField("errors", result.Errors).Error("Execute query error(s)")
//}
render.JSON(w, r, result)
}