Skip to content

Commit

Permalink
feat: allow single, unnamed, queries
Browse files Browse the repository at this point in the history
Allow single, unnamed, queries
  • Loading branch information
gajus authored Sep 20, 2017
2 parents f5001f4 + 99c2ebe commit 816b782
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,13 @@ export default () => {

const queryDocument = gql(source);

for (const definition of queryDocument.definitions) {
if (!definition.name) {
throw new Error('GraphQL query must have name.');
// If a document contains only one operation, that operation may be unnamed:
// https://facebook.github.io/graphql/#sec-Language.Query-Document
if (queryDocument.definitions.length > 1) {
for (const definition of queryDocument.definitions) {
if (!definition.name) {
throw new Error('GraphQL query must have name.');
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import gql from 'graphql-tag';

const foo = gql`{foo}`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const foo = {
'kind': 'Document',
'definitions': [{
'kind': 'OperationDefinition',
'operation': 'query',
'name': null,
'variableDefinitions': null,
'directives': [],
'selectionSet': {
'kind': 'SelectionSet',
'selections': [{
'kind': 'Field',
'alias': null,
'name': {
'kind': 'Name',
'value': 'foo'
},
'arguments': [],
'directives': [],
'selectionSet': null
}]
}
}],
'loc': {
'start': 0,
'end': 5,
'source': {
'body': '{foo}',
'name': 'GraphQL request',
'locationOffset': {
'line': 1,
'column': 1
}
}
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"plugins": [
[
"../../../../src"
]
]
}
29 changes: 29 additions & 0 deletions test/unnamed-query-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { transform } from 'babel-core';
import assert from 'assert';

const fixture = "gql`type Widget { name: String } query {widget}`";

describe("When given an unnamed query", () => {
let originalError;

before(function() {
originalError = console.error;
});

after(function() {
console.error = originalError;
});

it('fails when there are other definitions', () => {
const calls = [];

console.error = (...args) => calls.push(args.join(' '));

transform(fixture, {
plugins: [['./src']]
});

assert.equal(calls.length, 1);
assert.equal(calls[0], 'error Error: GraphQL query must have name.');
});
});

0 comments on commit 816b782

Please sign in to comment.