From b5dd7af9e91d9f01eead15f861d5b84f55f90d7d Mon Sep 17 00:00:00 2001 From: Adam Date: Thu, 20 Feb 2020 13:02:56 +1100 Subject: [PATCH] Add function to check presense of operation context --- graphql/context_operation.go | 8 ++++++++ graphql/context_operation_test.go | 17 ++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/graphql/context_operation.go b/graphql/context_operation.go index 3d74a806de6..d19b9fd3452 100644 --- a/graphql/context_operation.go +++ b/graphql/context_operation.go @@ -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) diff --git a/graphql/context_operation_test.go b/graphql/context_operation_test.go index bb4d9212aba..36ffbcc975c 100644 --- a/graphql/context_operation_test.go +++ b/graphql/context_operation_test.go @@ -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) {