Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add utility to normalize graphql request #29

Merged
merged 1 commit into from
May 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 4 additions & 32 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"errors"
"io/ioutil"
"net/http"
"strings"
"time"

"github.com/99designs/gqlgen/graphql/handler"
Expand All @@ -15,9 +14,7 @@ import (
"github.com/gbox-proxy/gbox/admin/generated"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/jensneuse/graphql-go-tools/pkg/astparser"
"github.com/jensneuse/graphql-go-tools/pkg/graphql"
"github.com/jensneuse/graphql-go-tools/pkg/operationreport"
"go.uber.org/zap"
)

Expand Down Expand Up @@ -78,7 +75,7 @@ func (h *Handler) GraphQLOverWebsocketHandle(w http.ResponseWriter, r *http.Requ
}

n := r.Context().Value(nextHandlerCtxKey).(caddyhttp.Handler)
mr := newWebsocketMetricsResponseWriter(w, h)
mr := newWebsocketMetricsResponseWriter(w, h.schema, h)
reporter.error = h.ReverseProxy.ServeHTTP(mr, r, n)
}

Expand Down Expand Up @@ -153,39 +150,14 @@ func (h *Handler) unmarshalHTTPRequest(r *http.Request) (*graphql.Request, error
return nil, err
}

err = graphql.UnmarshalHttpRequest(copyHTTPRequest, gqlRequest)

if err != nil {
if err = graphql.UnmarshalHttpRequest(copyHTTPRequest, gqlRequest); err != nil {
return nil, err
}

if result, _ := gqlRequest.Normalize(h.schema); !result.Successful {
return nil, 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 nil, report
}

if operationName == "" && numOfOperations == 1 {
operationName = operation.OperationDefinitionNameString(0)
}

if !operation.OperationNameExists(operationName) {
report.AddExternalError(operationreport.ErrOperationWithProvidedOperationNameNotFound(operationName))

return nil, report
if err = normalizeGraphqlRequest(h.schema, gqlRequest); err != nil {
return nil, err
}

gqlRequest.OperationName = operationName

return gqlRequest, nil
}

Expand Down
34 changes: 34 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ 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{
Expand All @@ -24,3 +27,34 @@ func writeResponseErrors(errors error, w http.ResponseWriter) error {

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
}
16 changes: 12 additions & 4 deletions ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@ import (
type wsMetricsResponseWriter struct {
requestMetrics
*caddyhttp.ResponseWriterWrapper
schema *graphql.Schema
}

func newWebsocketMetricsResponseWriter(w http.ResponseWriter, rm requestMetrics) *wsMetricsResponseWriter {
func newWebsocketMetricsResponseWriter(w http.ResponseWriter, s *graphql.Schema, rm requestMetrics) *wsMetricsResponseWriter {
return &wsMetricsResponseWriter{
requestMetrics: rm,
ResponseWriterWrapper: &caddyhttp.ResponseWriterWrapper{
ResponseWriter: w,
},
schema: s,
requestMetrics: rm,
}
}

Expand All @@ -35,6 +37,7 @@ func (r *wsMetricsResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
c = &wsMetricsConn{
Conn: c,
requestMetrics: r.requestMetrics,
schema: r.schema,
}
}

Expand All @@ -45,14 +48,15 @@ type wsMetricsConn struct {
net.Conn
requestMetrics
request *graphql.Request
schema *graphql.Schema
subscribeAt time.Time
}

func (c *wsMetricsConn) Read(b []byte) (n int, err error) {
n, err = c.Conn.Read(b)

if err != nil {
if c.request != nil {
if c.request != nil || err != nil {
if err != nil {
c.addMetricsEndRequest(c.request, time.Since(c.subscribeAt))
c.request = nil
}
Expand Down Expand Up @@ -88,6 +92,10 @@ func (c *wsMetricsConn) Read(b []byte) (n int, err error) {
return n, err
}

if e := normalizeGraphqlRequest(c.schema, request); e != nil {
return n, err
}

c.request = request
c.subscribeAt = time.Now()
c.addMetricsBeginRequest(request)
Expand Down
22 changes: 20 additions & 2 deletions ws_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,17 @@ func (m *testRequestMetrics) addMetricsEndRequest(request *graphql.Request, dura
}

func TestWsMetricsConn(t *testing.T) {
s, _ := graphql.NewSchemaFromString(`
type Query {
users [User!]!
}

type User {
id: ID!
}
`)
m := newTestRequestMetrics(t)
w := newWebsocketMetricsResponseWriter(&testWsResponseWriter{}, m)
w := newWebsocketMetricsResponseWriter(&testWsResponseWriter{}, s, m)
conn, _, _ := w.Hijack()
buff := new(bytes.Buffer)
wsutil.WriteClientText(buff, []byte(`{"type": "start", "payload":{"query": "subscription { users { id } }"}}`))
Expand All @@ -76,6 +85,15 @@ func TestWsMetricsConn(t *testing.T) {
}

func TestWsMetricsConnBadCases(t *testing.T) {
s, _ := graphql.NewSchemaFromString(`
type Query {
users [User!]!
}

type User {
id: ID!
}
`)
testCases := map[string]struct {
message string
}{
Expand All @@ -93,7 +111,7 @@ func TestWsMetricsConnBadCases(t *testing.T) {

for name, testCase := range testCases {
m := newTestRequestMetrics(t)
w := newWebsocketMetricsResponseWriter(&testWsResponseWriter{}, m)
w := newWebsocketMetricsResponseWriter(&testWsResponseWriter{}, s, m)
conn, _, _ := w.Hijack()
buff := new(bytes.Buffer)

Expand Down