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

[RFC] Cache parsed and validated queries in memory #2170

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
51 changes: 33 additions & 18 deletions packages/apollo-server-core/src/requestPipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ export type DataSources<TContext> = {

type Mutable<T> = { -readonly [P in keyof T]: T[P] };

let cache: { [key: string]: DocumentNode } = {};

export async function processGraphQLRequest<TContext>(
config: GraphQLRequestPipelineConfig<TContext>,
requestContext: Mutable<GraphQLRequestContext<TContext>>,
Expand Down Expand Up @@ -168,29 +170,42 @@ export async function processGraphQLRequest<TContext>(
);

try {
let document: DocumentNode;
try {
document = parse(query);
parsingDidEnd();
} catch (syntaxError) {
parsingDidEnd(syntaxError);
return sendErrorResponse(syntaxError, SyntaxError);
}
let document: DocumentNode = cache[query];
if (!document) {
try {
document = parse(query);
parsingDidEnd();
} catch (syntaxError) {
parsingDidEnd(syntaxError);
return sendErrorResponse(syntaxError, SyntaxError);
}

requestContext.document = document;
requestContext.document = document;

const validationDidEnd = await dispatcher.invokeDidStartHook(
'validationDidStart',
requestContext as WithRequired<typeof requestContext, 'document'>,
);
const validationDidEnd = await dispatcher.invokeDidStartHook(
'validationDidStart',
requestContext as WithRequired<typeof requestContext, 'document'>,
);

const validationErrors = validate(document);
const validationErrors = validate(document);

if (validationErrors.length === 0) {
validationDidEnd();
if (validationErrors.length === 0) {
validationDidEnd();
} else {
validationDidEnd(validationErrors);
return sendErrorResponse(validationErrors, ValidationError);
}

// If the query is parsed and validated correctly, cache the result
// in memory to speed up the next requests
cache[query] = document;
} else {
validationDidEnd(validationErrors);
return sendErrorResponse(validationErrors, ValidationError);
parsingDidEnd();
const validationDidEnd = await dispatcher.invokeDidStartHook(
'validationDidStart',
requestContext as WithRequired<typeof requestContext, 'document'>,
);
validationDidEnd();
}

// FIXME: If we want to guarantee an operation has been set when invoking
Expand Down