From 1374b2e9e78b3b9bac3c3add73e0a1c2bb7ae6f0 Mon Sep 17 00:00:00 2001 From: Taeho Kim Date: Thu, 9 Jul 2015 00:11:30 +0900 Subject: [PATCH] Prevent more than one type of the same name --- src/type/__tests__/schema.js | 42 ++++++++++++++++++++++++++++++++++++ src/type/schema.js | 26 ++++++++++++++++------ 2 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 src/type/__tests__/schema.js diff --git a/src/type/__tests__/schema.js b/src/type/__tests__/schema.js new file mode 100644 index 0000000000..097e089dae --- /dev/null +++ b/src/type/__tests__/schema.js @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +import { + GraphQLSchema, + GraphQLObjectType, +} from '../'; + +import { describe, it } from 'mocha'; +import { expect } from 'chai'; + +describe('Type System: Schema', () => { + it('does not allow more than one type of the same name', () => { + var A = new GraphQLObjectType({ + name: 'SameName', + fields: {} + }); + + var B = new GraphQLObjectType({ + name: 'SameName', + fields: {} + }); + + var SomeQuery = new GraphQLObjectType({ + name: 'SomeQuery', + fields: { + a: { type: A }, + b: { type: B } + } + }); + + expect( + () => new GraphQLSchema({ query: SomeQuery }) + ).to.throw('Schema cannot contain more than one type named SameName.'); + }); +}); diff --git a/src/type/schema.js b/src/type/schema.js index 499ecde1ec..f311ea1853 100644 --- a/src/type/schema.js +++ b/src/type/schema.js @@ -44,6 +44,7 @@ export class GraphQLSchema { constructor(config: GraphQLSchemaConfig) { this._schemaConfig = config; + this._typeMap = buildTypeMap(this); } getQueryType(): GraphQLObjectType { @@ -55,11 +56,7 @@ export class GraphQLSchema { } getTypeMap(): TypeMap { - return this._typeMap || (this._typeMap = [ - this.getQueryType(), - this.getMutationType(), - __Schema - ].reduce(typeMapReducer, {})); + return this._typeMap; } getType(name: string): ?GraphQLType { @@ -85,11 +82,28 @@ type GraphQLSchemaConfig = { mutation?: ?GraphQLObjectType; } +function buildTypeMap(schema: GraphQLSchema): TypeMap { + return [ + schema.getQueryType(), + schema.getMutationType(), + __Schema + ].reduce(typeMapReducer, {}); +} + export function typeMapReducer(map: TypeMap, type: ?GraphQLType): TypeMap { if (type instanceof GraphQLList || type instanceof GraphQLNonNull) { return typeMapReducer(map, type.ofType); } - if (!type || map[type.name]) { + if (!type) { + return map; + } + var prevType = map[type.name]; + if (prevType) { + if (prevType !== type) { + throw new Error( + `Schema cannot contain more than one type named ${type.name}.` + ); + } return map; } map[type.name] = type;