Skip to content

Commit 434bccd

Browse files
committed
chore: prevent batching of root queries/mutations in a single operation
1 parent 76f39e9 commit 434bccd

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

packages/backend/src/helpers/graphql-instance.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { ApolloServerPluginLandingPageDisabled } from '@apollo/server/plugin/dis
44
import { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default'
55
import { makeExecutableSchema } from '@graphql-tools/schema'
66
import { RequestHandler } from 'express'
7+
import { Kind, OperationDefinitionNode } from 'graphql/language'
78
import { applyMiddleware } from 'graphql-middleware'
89

910
import appConfig from '@/config/app'
@@ -42,6 +43,31 @@ function ApolloServerPluginUserTracer(): ApolloServerPlugin<AuthenticatedContext
4243
}
4344
}
4445

46+
function preventBatching(): ApolloServerPlugin {
47+
return {
48+
async requestDidStart() {
49+
return {
50+
async didResolveOperation(requestContext) {
51+
const { document } = requestContext
52+
// There should only be one operation definition per document
53+
const queryDefinition = document.definitions.find(
54+
(definition) => definition.kind === Kind.OPERATION_DEFINITION,
55+
) as OperationDefinitionNode | undefined
56+
57+
if (queryDefinition) {
58+
// Check if there are multiple selections (root fields) in the query
59+
if (queryDefinition.selectionSet.selections.length > 1) {
60+
throw new Error(
61+
'Multiple root fields in a single operation are not allowed.',
62+
)
63+
}
64+
}
65+
},
66+
}
67+
},
68+
}
69+
}
70+
4571
const schema = makeExecutableSchema({ typeDefs, resolvers })
4672

4773
const schemaWithMiddleware = applyMiddleware(
@@ -57,6 +83,7 @@ const server = new ApolloServer<UnauthenticatedContext>({
5783
? ApolloServerPluginLandingPageLocalDefault()
5884
: ApolloServerPluginLandingPageDisabled(),
5985
ApolloServerPluginUserTracer(),
86+
preventBatching(),
6087
],
6188
formatError: (error) => {
6289
logger.error(error)

0 commit comments

Comments
 (0)