Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/type/__tests__/schema.js
Original file line number Diff line number Diff line change
@@ -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.');
});
});
26 changes: 20 additions & 6 deletions src/type/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export class GraphQLSchema {

constructor(config: GraphQLSchemaConfig) {
this._schemaConfig = config;
this._typeMap = buildTypeMap(this);
}

getQueryType(): GraphQLObjectType {
Expand All @@ -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 {
Expand All @@ -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;
Expand Down