diff --git a/app/assets/javascripts/entrypoints/graphql_explorer.js b/app/assets/javascripts/entrypoints/graphql_explorer.js index 88b86371ead4a26e545fae4c59a510ccb3f00894..a21d91fefba6b88c58fdae6e22797f92d4da948b 100644 --- a/app/assets/javascripts/entrypoints/graphql_explorer.js +++ b/app/assets/javascripts/entrypoints/graphql_explorer.js @@ -19,8 +19,28 @@ const apolloClient = createDefaultClient( const graphiqlContainer = document.getElementById('graphiql-container'); function apolloFetcher(graphQLParams) { + let query = gql(graphQLParams.query); + + /* + GraphiQL allows multiple named operations to be declared in the editor. + When the user clicks execute, they are prompted to select one of the operations. + We must filter the query to only contain the selected operation so we execute the correct query + and avoid an `Ambiguous GraphQL document: contains 2 operations` error. + */ + if (graphQLParams.operationName) { + query = { + ...query, + definitions: query.definitions.filter((definition) => { + return ( + definition.kind !== 'OperationDefinition' || + definition.name.value === graphQLParams.operationName + ); + }), + }; + } + return apolloClient.subscribe({ - query: gql(graphQLParams.query), + query, variables: graphQLParams.variables, operationName: graphQLParams.operationName, }); diff --git a/spec/features/api/graphql/graphql_explorer_spec.rb b/spec/features/api/graphql/graphql_explorer_spec.rb index bae4a768f74182c06ac63be64405e5db4796805c..7c8ddbc59516ccbd1fd9f8ab4493d34242a60dad 100644 --- a/spec/features/api/graphql/graphql_explorer_spec.rb +++ b/spec/features/api/graphql/graphql_explorer_spec.rb @@ -44,6 +44,22 @@ expect_response(%("currentUser": { "id": "#{user.to_gid}" })) end + it 'allows user to execute one of multiple named queries' do + visit '/-/graphql-explorer' + + fill_in_editor( + 'query currentUserId { currentUser { ...UserIdFragment } } ' \ + 'query currentUsername { currentUser { username } } ' \ + 'fragment UserIdFragment on User { id }' + ) + sleep 0.1 # GraphiQL needs to parse the query in the background before we click execute + + click_execute_button + find('.graphiql-dropdown-item', text: 'currentUserId').click + + expect_response(%("currentUser": { "id": "#{user.to_gid}" })) + end + it 'allows user to execute a mutation' do visit '/-/graphql-explorer'