Skip to content

Commit

Permalink
Add function to check presense of operation context
Browse files Browse the repository at this point in the history
  • Loading branch information
vektah committed Feb 20, 2020
1 parent 69d6c4b commit b5dd7af
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 b5dd7af

Please sign in to comment.