-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.go
60 lines (45 loc) · 1.47 KB
/
utils.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
package gbox
import (
"bytes"
"net/http"
"strings"
"sync"
"github.com/jensneuse/graphql-go-tools/pkg/astparser"
"github.com/jensneuse/graphql-go-tools/pkg/graphql"
"github.com/jensneuse/graphql-go-tools/pkg/operationreport"
)
var bufferPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
func writeResponseErrors(errors error, w http.ResponseWriter) error {
gqlErrors := graphql.RequestErrorsFromError(errors)
w.Header().Set("Content-Type", "application/json")
if _, err := gqlErrors.WriteResponse(w); err != nil {
return err
}
return nil
}
func normalizeGraphqlRequest(schema *graphql.Schema, gqlRequest *graphql.Request) error {
if result, _ := gqlRequest.Normalize(schema); !result.Successful {
return result.Errors
}
operation, _ := astparser.ParseGraphqlDocumentString(gqlRequest.Query)
numOfOperations := operation.NumOfOperationDefinitions()
operationName := strings.TrimSpace(gqlRequest.OperationName)
report := &operationreport.Report{}
if operationName == "" && numOfOperations > 1 {
report.AddExternalError(operationreport.ErrRequiredOperationNameIsMissing())
return report
}
if operationName == "" && numOfOperations == 1 {
operationName = operation.OperationDefinitionNameString(0)
}
if !operation.OperationNameExists(operationName) {
report.AddExternalError(operationreport.ErrOperationWithProvidedOperationNameNotFound(operationName))
return report
}
gqlRequest.OperationName = operationName
return nil
}