-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphqlHandler.go
133 lines (113 loc) · 3.15 KB
/
graphqlHandler.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package gqlhandler
import (
"encoding/json"
"go-graphql-mongo-server/common"
"go-graphql-mongo-server/config"
"go-graphql-mongo-server/gqlhandler/mutation"
"go-graphql-mongo-server/gqlhandler/query"
"go-graphql-mongo-server/logger"
"go-graphql-mongo-server/models"
"io"
"net/http"
"github.com/graphql-go/graphql"
)
var SchemaQl, _ = graphql.NewSchema(graphql.SchemaConfig{
Query: rootQuery,
Mutation: rootMutation,
})
var mutationMap = graphql.Fields{
mutation.UserMutation.Name: mutation.UserMutation,
mutation.CreateTokenMutation.Name: mutation.CreateTokenMutation,
mutation.RevokeTokenMutation.Name: mutation.RevokeTokenMutation,
}
var queryMap = graphql.Fields{
query.UsersQuery.Name: query.UsersQuery,
query.TokenQuery.Name: query.TokenQuery,
}
var rootMutation = graphql.NewObject(graphql.ObjectConfig{
Name: "Mutation",
Fields: mutationMap,
})
var rootQuery = graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: queryMap,
})
func GraphqlHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
ctx := r.Context()
queryBody, err := io.ReadAll(r.Body)
if err != nil {
handleError("Error in reading request body", err, w)
return
}
requests, err := getRequest(queryBody)
if err != nil {
handleError("Error in parsing request body", err, w)
return
}
var resultMap []*graphql.Result
var errorCount int
for _, request := range requests {
result := graphql.Do(graphql.Params{
Schema: SchemaQl,
RequestString: request.Query,
VariableValues: request.Variables,
Context: ctx,
})
resultMap = append(resultMap, result)
if result.HasErrors() {
errorCount++
}
}
if len(requests) == errorCount {
w.WriteHeader(http.StatusBadRequest)
} else {
w.WriteHeader(http.StatusOK)
}
if len(resultMap) > 0 {
var response []byte
if len(resultMap) == 1 {
response, _ = json.Marshal(resultMap[0])
} else {
response, _ = json.Marshal(resultMap)
}
// Set HSTS header is HTTPS is enabled
if config.Store.HTTPSCert.HTTPSEnabled {
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
}
_, err = w.Write(response)
if err != nil {
logger.Log.Errorf("Error in writing response %+v", err)
}
}
}
func getRequest(queryBody []byte) ([]models.GQLRequestBody, error) {
var requests []models.GQLRequestBody
var err error
queryBodyString := string(queryBody)
if queryBodyString[0] == '[' {
err = json.Unmarshal(queryBody, &requests)
if err != nil {
return nil, err
}
} else {
jsonMap := make(map[string]interface{})
err = json.Unmarshal(queryBody, &jsonMap)
if err != nil {
return nil, err
}
variables := make(map[string]interface{})
if jsonMap["variables"] != nil {
variables = jsonMap["variables"].(map[string]interface{})
}
requests = append(requests, models.GQLRequestBody{
Query: jsonMap["query"].(string),
Variables: variables,
})
}
return requests, nil
}
func handleError(text string, err error, w http.ResponseWriter) {
logger.Log.Errorf("%v : %+v", text, err)
common.RespondWithJSON(w, http.StatusBadRequest, `{"errors": [{"message": "`+err.Error()+`"}]}`)
}