Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add validationMaxErrors option #8014

Open
wants to merge 2 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
12 changes: 12 additions & 0 deletions .changeset/validate-options.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@apollo/server': minor
---

Expose `graphql` validation options.

```
const server = new ApolloServer({
typeDefs,
resolvers,
validateOptions: { maxErrors: 10 },
});
5 changes: 5 additions & 0 deletions packages/server/src/ApolloServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
assertValidSchema,
print,
printSchema,
type validate,
type DocumentNode,
type FormattedExecutionResult,
type GraphQLFieldResolver,
Expand Down Expand Up @@ -152,6 +153,8 @@ type ServerState =
stopError: Error | null;
};

export type ValidateOptions = NonNullable<Parameters<typeof validate>[3]>;

export interface ApolloServerInternals<TContext extends BaseContext> {
state: ServerState;
gatewayExecutor: GatewayExecutor | null;
Expand All @@ -167,6 +170,7 @@ export interface ApolloServerInternals<TContext extends BaseContext> {
apolloConfig: ApolloConfig;
plugins: ApolloServerPlugin<TContext>[];
parseOptions: ParseOptions;
validationOptions: ValidateOptions;
// `undefined` means we figure out what to do during _start (because
// the default depends on whether or not we used the background version
// of start).
Expand Down Expand Up @@ -304,6 +308,7 @@ export class ApolloServer<in out TContext extends BaseContext = BaseContext> {
hideSchemaDetailsFromClientErrors,
dangerouslyDisableValidation:
config.dangerouslyDisableValidation ?? false,
validationOptions: config.validationOptions ?? {},
fieldResolver: config.fieldResolver,
includeStacktraceInErrorResponses:
config.includeStacktraceInErrorResponses ??
Expand Down
4 changes: 3 additions & 1 deletion packages/server/src/__tests__/ApolloServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,9 @@ describe('ApolloServer start', () => {
});
});

function singleResult(body: GraphQLResponseBody): FormattedExecutionResult {
export function singleResult(
body: GraphQLResponseBody,
): FormattedExecutionResult {
if (body.kind === 'single') {
return body.singleResult;
}
Expand Down
49 changes: 49 additions & 0 deletions packages/server/src/__tests__/runQuery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
} from '..';
import { mockLogger } from './mockLogger';
import { jest, describe, it, expect } from '@jest/globals';
import { singleResult } from './ApolloServer.test';

async function runQuery(
config: ApolloServerOptions<BaseContext>,
Expand Down Expand Up @@ -1192,4 +1193,52 @@ describe('parsing and validation cache', () => {
expect(parsingDidStart.mock.calls.length).toBe(6);
expect(validationDidStart.mock.calls.length).toBe(6);
});

describe('validationMaxErrors option', () => {
it('should be 100 by default', async () => {
const server = new ApolloServer({
schema,
});
await server.start();

const vars = new Array(1000).fill('$a:a').join(',');
const query = `query aaa (${vars}) { a }`;

const res = await server.executeOperation({ query });
expect(res.http.status).toBe(400);

const body = singleResult(res.body);

// 100 by default plus one "Too many validation errors" error
// https://github.com/graphql/graphql-js/blob/main/src/validation/validate.ts#L46
expect(body.errors).toHaveLength(101);
await server.stop();
});

it('aborts the validation if max errors more than expected', async () => {
const server = new ApolloServer({
schema,
validationOptions: { maxErrors: 1 },
});
await server.start();

const vars = new Array(1000).fill('$a:a').join(',');
const query = `query aaa (${vars}) { a }`;

const res = await server.executeOperation({ query });
expect(res.http.status).toBe(400);

const body = singleResult(res.body);

expect(body.errors).toHaveLength(2);
expect(body.errors?.[0]).toMatchObject({
message: `There can be only one variable named "$a".`,
});
expect(body.errors?.[1]).toMatchObject({
message: `Too many validation errors, error limit reached. Validation aborted.`,
});

await server.stop();
});
});
});
2 changes: 2 additions & 0 deletions packages/server/src/externalTypes/constructor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type { GatewayInterface } from '@apollo/server-gateway-interface';
import type { ApolloServerPlugin } from './plugins.js';
import type { BaseContext } from './index.js';
import type { GraphQLExperimentalIncrementalExecutionResults } from '../incrementalDeliveryPolyfill.js';
import type { ValidateOptions } from '../ApolloServer.js';

export type DocumentStore = KeyValueCache<DocumentNode>;

Expand Down Expand Up @@ -101,6 +102,7 @@ interface ApolloServerOptionsBase<TContext extends BaseContext> {
nodeEnv?: string;
documentStore?: DocumentStore | null;
dangerouslyDisableValidation?: boolean;
validationOptions?: ValidateOptions;
csrfPrevention?: CSRFPreventionOptions | boolean;

// Used for parsing operations; unlike in AS3, this is not also used for
Expand Down
1 change: 1 addition & 0 deletions packages/server/src/requestPipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ export async function processGraphQLRequest<TContext extends BaseContext>(
schemaDerivedData.schema,
requestContext.document,
[...specifiedRules, ...internals.validationRules],
internals.validationOptions,
);

if (validationErrors.length === 0) {
Expand Down