Skip to content

Commit

Permalink
add fixed complexity limit
Browse files Browse the repository at this point in the history
  • Loading branch information
vektah committed Nov 11, 2019
1 parent f2ef5ec commit 0a39ae2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
7 changes: 7 additions & 0 deletions graphql/handler/extension/complexity.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ type ComplexityLimit func(ctx context.Context, rc *graphql.OperationContext) int

var _ graphql.OperationContextMutator = ComplexityLimit(func(ctx context.Context, rc *graphql.OperationContext) int { return 0 })

// FixedComplexityLimit sets a complexity limit that does not change
func FixedComplexityLimit(limit int) graphql.HandlerExtension {
return ComplexityLimit(func(ctx context.Context, rc *graphql.OperationContext) int {
return limit
})
}

func (c ComplexityLimit) MutateOperationContext(ctx context.Context, rc *graphql.OperationContext) *gqlerror.Error {
es := graphql.GetServerContext(ctx)
op := rc.Doc.Operations.ForName(rc.OperationName)
Expand Down
20 changes: 20 additions & 0 deletions graphql/handler/extension/complexity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,26 @@ func TestHandlerComplexity(t *testing.T) {
})
}

func TestFixedComplexity(t *testing.T) {
h := testserver.New()
h.Use(extension.FixedComplexityLimit(2))
h.AddTransport(&transport.POST{})

t.Run("below complexity limit", func(t *testing.T) {
h.SetCalculatedComplexity(2)
resp := doRequest(h, "POST", "/graphql", `{"query":"{ name }"}`)
require.Equal(t, http.StatusOK, resp.Code, resp.Body.String())
require.Equal(t, `{"data":{"name":"test"}}`, resp.Body.String())
})

t.Run("above complexity limit", func(t *testing.T) {
h.SetCalculatedComplexity(4)
resp := doRequest(h, "POST", "/graphql", `{"query":"{ name }"}`)
require.Equal(t, http.StatusUnprocessableEntity, resp.Code, resp.Body.String())
require.Equal(t, `{"errors":[{"message":"operation has complexity 4, which exceeds the limit of 2"}],"data":null}`, resp.Body.String())
})
}

func doRequest(handler http.Handler, method string, target string, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, target, strings.NewReader(body))
r.Header.Set("Content-Type", "application/json")
Expand Down

0 comments on commit 0a39ae2

Please sign in to comment.