Skip to content

Commit

Permalink
Stop GetResolverContext from panicking when missing
Browse files Browse the repository at this point in the history
  • Loading branch information
lwc committed Feb 4, 2019
1 parent 055fb4b commit c1b50ce
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
14 changes: 7 additions & 7 deletions graphql/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,10 @@ const (
)

func GetRequestContext(ctx context.Context) *RequestContext {
val := ctx.Value(request)
if val == nil {
return nil
if val, ok := ctx.Value(request).(*RequestContext); ok {
return val
}

return val.(*RequestContext)
return nil
}

func WithRequestContext(ctx context.Context, rc *RequestContext) context.Context {
Expand Down Expand Up @@ -117,8 +115,10 @@ func (r *ResolverContext) Path() []interface{} {
}

func GetResolverContext(ctx context.Context) *ResolverContext {
val, _ := ctx.Value(resolver).(*ResolverContext)
return val
if val, ok := ctx.Value(resolver).(*ResolverContext); ok {
return val
}
return nil
}

func WithResolverContext(ctx context.Context, rc *ResolverContext) context.Context {
Expand Down
15 changes: 15 additions & 0 deletions graphql/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/vektah/gqlparser/ast"
)

Expand Down Expand Up @@ -63,3 +64,17 @@ func TestRequestContext_GetErrors(t *testing.T) {
})
}
}

func TestGetRequestContext(t *testing.T) {
require.Nil(t, GetRequestContext(context.Background()))

rc := &RequestContext{}
require.Equal(t, rc, GetRequestContext(WithRequestContext(context.Background(), rc)))
}

func TestGetResolverContext(t *testing.T) {
require.Nil(t, GetResolverContext(context.Background()))

rc := &ResolverContext{}
require.Equal(t, rc, GetResolverContext(WithResolverContext(context.Background(), rc)))
}

0 comments on commit c1b50ce

Please sign in to comment.