Skip to content
This repository has been archived by the owner on Mar 20, 2023. It is now read-only.

Validate static schema on middleware mount #698

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
29 changes: 29 additions & 0 deletions src/__tests__/http-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,35 @@ function runTests(server: Server) {
});
});

it('Reports validation errors for dynamic schema', async () => {
const app = server();

app.get(
urlString(),
graphqlHTTP(() => Promise.resolve({ schema: TestSchema })),
);

const response = await app.request().get(
urlString({
query: '{ test, unknownOne, unknownTwo }',
}),
);

expect(response.status).to.equal(400);
expect(JSON.parse(response.text)).to.deep.equal({
errors: [
{
message: 'Cannot query field "unknownOne" on type "QueryRoot".',
locations: [{ line: 1, column: 9 }],
},
{
message: 'Cannot query field "unknownTwo" on type "QueryRoot".',
locations: [{ line: 1, column: 21 }],
},
],
});
});

it('Errors when missing operation name', async () => {
const app = server();

Expand Down
15 changes: 15 additions & 0 deletions src/__tests__/usage-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,19 @@ describe('Useful errors when incorrectly used', () => {
],
});
});

it('requires a valid schema if static schema is defined in options', () => {
const options = () => ({
// @ts-expect-error
schema: new GraphQLSchema({ directives: [null] }),
});
const { schema } = options();
expect(() => {
graphqlHTTP({ schema });
}).to.throw('GraphQL schema validation failed');

expect(() => {
graphqlHTTP(options);
}).not.to.throw();
});
});
9 changes: 8 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,12 @@ export function graphqlHTTP(options: Options): Middleware {
throw new Error('GraphQL middleware requires options.');
}

const staticSchemaValidationErrors =
'schema' in options ? validateSchema(options.schema) : undefined;

if (staticSchemaValidationErrors?.length) {
throw Error('GraphQL schema validation failed');
}
return async function graphqlMiddleware(
request: Request,
response: Response,
Expand Down Expand Up @@ -272,7 +278,8 @@ export function graphqlHTTP(options: Options): Middleware {
}

// Validate Schema
const schemaValidationErrors = validateSchema(schema);
const schemaValidationErrors =
staticSchemaValidationErrors ?? validateSchema(schema);
if (schemaValidationErrors.length > 0) {
// Return 500: Internal Server Error if invalid schema.
throw httpError(500, 'GraphQL schema validation error.', {
Expand Down