Skip to content

Commit

Permalink
fix(graphql): ensure buildSchema fails on invalid GraphQL schema (#695)
Browse files Browse the repository at this point in the history
  • Loading branch information
benjie committed Nov 27, 2020
1 parent 72b4d2e commit c837e09
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
41 changes: 41 additions & 0 deletions packages/graphile-build/__tests__/invalid.test.js
@@ -0,0 +1,41 @@
const { buildSchema, defaultPlugins } = require("../");

const InvalidSchemaPlugin = builder => {
builder.hook("GraphQLObjectType:fields", (fields, build, context) => {
if (!context.scope.isRootQuery) {
return fields;
}
return build.extend(fields, {
invalidField: {
type: build.graphql.GraphQLInt,
args: {
invalidArgument: {
// Output types cannot be used as argument types
type: new build.graphql.GraphQLObjectType({
name: "OutputType",
fields: {
anything: {
type: build.graphql.GraphQLInt,
},
},
}),
},
},
},
});
});
};

test("throws error on invalid schema", async () => {
let error;
try {
await buildSchema([...defaultPlugins, InvalidSchemaPlugin]);
} catch (err) {
error = err;
}
expect(error).toBeTruthy();
expect(error).toMatchInlineSnapshot(`
[Error: GraphQL schema is invalid:
- The type of Query.invalidField(invalidArgument:) must be Input Type but got: OutputType.]
`);
});
10 changes: 9 additions & 1 deletion packages/graphile-build/src/SchemaBuilder.js
Expand Up @@ -488,13 +488,21 @@ class SchemaBuilder extends EventEmitter {
isSchema: true,
}
);
this._generatedSchema = this.applyHooks(
const hookedSchema = this.applyHooks(
build,
"finalize",
schema,
{},
"Finalising GraphQL schema"
);
const errors = build.graphql.validateSchema(hookedSchema);
if (errors && errors.length) {
throw new Error(
"GraphQL schema is invalid:\n" +
errors.map(e => `- ` + e.message.replace(/\n/g, "\n ")).join("\n")
);
}
this._generatedSchema = hookedSchema;
}
if (!this._generatedSchema) {
throw new Error("Schema generation failed");
Expand Down

0 comments on commit c837e09

Please sign in to comment.