Skip to content

Commit c837e09

Browse files
authored
fix(graphql): ensure buildSchema fails on invalid GraphQL schema (#695)
1 parent 72b4d2e commit c837e09

2 files changed

Lines changed: 50 additions & 1 deletion

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
const { buildSchema, defaultPlugins } = require("../");
2+
3+
const InvalidSchemaPlugin = builder => {
4+
builder.hook("GraphQLObjectType:fields", (fields, build, context) => {
5+
if (!context.scope.isRootQuery) {
6+
return fields;
7+
}
8+
return build.extend(fields, {
9+
invalidField: {
10+
type: build.graphql.GraphQLInt,
11+
args: {
12+
invalidArgument: {
13+
// Output types cannot be used as argument types
14+
type: new build.graphql.GraphQLObjectType({
15+
name: "OutputType",
16+
fields: {
17+
anything: {
18+
type: build.graphql.GraphQLInt,
19+
},
20+
},
21+
}),
22+
},
23+
},
24+
},
25+
});
26+
});
27+
};
28+
29+
test("throws error on invalid schema", async () => {
30+
let error;
31+
try {
32+
await buildSchema([...defaultPlugins, InvalidSchemaPlugin]);
33+
} catch (err) {
34+
error = err;
35+
}
36+
expect(error).toBeTruthy();
37+
expect(error).toMatchInlineSnapshot(`
38+
[Error: GraphQL schema is invalid:
39+
- The type of Query.invalidField(invalidArgument:) must be Input Type but got: OutputType.]
40+
`);
41+
});

packages/graphile-build/src/SchemaBuilder.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -488,13 +488,21 @@ class SchemaBuilder extends EventEmitter {
488488
isSchema: true,
489489
}
490490
);
491-
this._generatedSchema = this.applyHooks(
491+
const hookedSchema = this.applyHooks(
492492
build,
493493
"finalize",
494494
schema,
495495
{},
496496
"Finalising GraphQL schema"
497497
);
498+
const errors = build.graphql.validateSchema(hookedSchema);
499+
if (errors && errors.length) {
500+
throw new Error(
501+
"GraphQL schema is invalid:\n" +
502+
errors.map(e => `- ` + e.message.replace(/\n/g, "\n ")).join("\n")
503+
);
504+
}
505+
this._generatedSchema = hookedSchema;
498506
}
499507
if (!this._generatedSchema) {
500508
throw new Error("Schema generation failed");

0 commit comments

Comments
 (0)