From 95e453bfe6db62ee00faa2bd66cd64b537721f04 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 3d74a806de..d19b9fd345 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 bb4d9212ab..36ffbcc975 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) {