From 6dd1fe7f82d58d20e348bf90c737d8844fc6f7d6 Mon Sep 17 00:00:00 2001 From: Matt Fong Date: Wed, 19 Feb 2020 06:06:18 -0800 Subject: [PATCH] fix: service field context (#50) * fix service field context * require keyword context * switch to positional arguments instead of keyword * adds tests * rubocop * switch back to keyword arguments --- lib/apollo-federation/service_field.rb | 2 +- spec/apollo-federation/service_field_spec.rb | 72 ++++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/lib/apollo-federation/service_field.rb b/lib/apollo-federation/service_field.rb index 8e9c8d523..609bb9d7b 100644 --- a/lib/apollo-federation/service_field.rb +++ b/lib/apollo-federation/service_field.rb @@ -10,7 +10,7 @@ module ServiceField field(:_service, Service, null: false) def _service - { sdl: context.schema.class.federation_sdl(context) } + { sdl: context.schema.class.federation_sdl(context: context) } end end end diff --git a/spec/apollo-federation/service_field_spec.rb b/spec/apollo-federation/service_field_spec.rb index cc9f2f004..96bb9724d 100644 --- a/spec/apollo-federation/service_field_spec.rb +++ b/spec/apollo-federation/service_field_spec.rb @@ -371,4 +371,76 @@ def execute_sdl(schema) GRAPHQL ) end + + context 'with a filter' do + let(:schema) do + product = Class.new(base_object) do + graphql_name 'Product' + + field :upc, String, null: false + end + + query_obj = Class.new(base_object) do + graphql_name 'Query' + + field :product, product, null: true + end + + Class.new(base_schema) do + query query_obj + end + end + let(:filter) do + class PermissionWhitelist + def call(_schema_member, context) + context[:user_role] == :admin + end + end + + PermissionWhitelist.new + end + let(:context) { { user_role: :admin } } + let(:executed_with_context) do + schema.execute('{ _service { sdl } }', only: filter, context: context) + end + let(:executed_without_context) { schema.execute('{ _service { sdl } }', only: filter) } + + it 'passes context to filters' do + expect(executed_with_context['data']['_service']['sdl']).to match_sdl( + <<~GRAPHQL, + type Product { + upc: String! + } + + type Query { + product: Product + } + GRAPHQL + ) + end + + it 'works without context' do + expect(executed_without_context['errors']).to( + match_array( + [ + include('message' => "Field '_service' doesn't exist on type 'Query'"), + ], + ), + ) + end + + context 'when not authorized' do + let(:context) { { user_role: :foo } } + + it 'returns an error message' do + expect(executed_with_context['errors']).to( + match_array( + [ + include('message' => "Field '_service' doesn't exist on type 'Query'"), + ], + ), + ) + end + end + end end