Skip to content

Commit

Permalink
Merge pull request #692 from graphql/dunder-warn
Browse files Browse the repository at this point in the history
Convert error to warning for non-compliant use of __
  • Loading branch information
leebyron authored Jan 26, 2017
2 parents 024f9f7 + fe34619 commit 80f5ecb
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 12 deletions.
25 changes: 18 additions & 7 deletions src/type/__tests__/validation-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -341,15 +341,26 @@ describe('Type System: Objects must have fields', () => {
);
});

it('rejects an Object type with reserved named fields', () => {
expect(
() => schemaWithFieldType(new GraphQLObjectType({
it('warns about an Object type with reserved named fields', () => {
/* eslint-disable no-console */
const realConsoleError = console.error;
const calls = [];
console.error = function () {
calls.push(Array.prototype.slice.call(arguments));
};
try {
schemaWithFieldType(new GraphQLObjectType({
name: 'SomeObject',
fields: { __notPartOfIntrospection: { type: GraphQLString } }
}))
).to.throw(
'Name "__notPartOfIntrospection" must not begin with "__", which is reserved by GraphQL introspection.'
);
}));

expect(calls[0][0]).contains(
'Name "__notPartOfIntrospection" must not begin with "__", which is reserved by GraphQL introspection.'
);
} finally {
console.error = realConsoleError;
}
/* eslint-enable no-console */
});

it('rejects an Object type with incorrectly typed fields', () => {
Expand Down
19 changes: 14 additions & 5 deletions src/utilities/assertValidName.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@

const NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/;

// Ensures console warnings are only issued once.
let hasWarnedAboutDunder = false;

/**
* Upholds the spec rules about naming.
*/
Expand All @@ -22,11 +25,17 @@ export function assertValidName(
`Must be named. Unexpected name: ${name}.`
);
}
if (!isIntrospection && name.slice(0, 2) === '__') {
throw new Error(
`Name "${name}" must not begin with "__", which is reserved by ` +
'GraphQL introspection.'
);
if (!isIntrospection && name.slice(0, 2) === '__' && !hasWarnedAboutDunder) {
hasWarnedAboutDunder = true;
/* eslint-disable no-console */
if (console && console.error) {
const error = new Error(
`Name "${name}" must not begin with "__", which is reserved by ` +
'GraphQL introspection.'
);
console.error(error.stack || String(error));
}
/* eslint-enable no-console */
}
if (!NAME_RX.test(name)) {
throw new Error(
Expand Down

0 comments on commit 80f5ecb

Please sign in to comment.