Skip to content

Commit

Permalink
Merge pull request #1051 from 99designs/has-operation-context
Browse files Browse the repository at this point in the history
Add function to check presense of operation context
  • Loading branch information
vektah committed Feb 20, 2020
2 parents d5d780c + 95e453b commit a53ce37
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
8 changes: 8 additions & 0 deletions graphql/context_operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,14 @@ func WithOperationContext(ctx context.Context, rc *OperationContext) context.Con
return context.WithValue(ctx, operationCtx, rc)
}

// HasOperationContext checks if the given context is part of an ongoing operation
//
// Some errors can happen outside of an operation, eg json unmarshal errors.
func HasOperationContext(ctx context.Context) bool {
_, ok := ctx.Value(operationCtx).(*OperationContext)
return ok
}

// This is just a convenient wrapper method for CollectFields
func CollectFieldsCtx(ctx context.Context, satisfies []string) []CollectedField {
resctx := GetFieldContext(ctx)
Expand Down
17 changes: 16 additions & 1 deletion graphql/context_operation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,22 @@ import (

func TestGetOperationContext(t *testing.T) {
rc := &OperationContext{}
require.Equal(t, rc, GetOperationContext(WithOperationContext(context.Background(), rc)))

t.Run("with operation context", func(t *testing.T) {
ctx := WithOperationContext(context.Background(), rc)

require.True(t, HasOperationContext(ctx))
require.Equal(t, rc, GetOperationContext(ctx))
})

t.Run("without operation context", func(t *testing.T) {
ctx := context.Background()

require.False(t, HasOperationContext(ctx))
require.Panics(t, func() {
GetOperationContext(ctx)
})
})
}

func TestCollectAllFields(t *testing.T) {
Expand Down

0 comments on commit a53ce37

Please sign in to comment.