Skip to content

Commit

Permalink
add query batch limit (subquery#2172)
Browse files Browse the repository at this point in the history
* add query batch limit

* update changelog

* update if statement
  • Loading branch information
bz888 authored Nov 21, 2023
1 parent b5193dd commit 179d9a8
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
2 changes: 2 additions & 0 deletions packages/query/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Added
- Allow restrictions on array based queries, with flag `--query-batch-limit` (#2172)

## [2.7.0] - 2023-11-15
### Added
Expand Down
23 changes: 21 additions & 2 deletions packages/query/src/graphql/graphql.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import {
ApolloServerPluginLandingPageDisabled,
ApolloServerPluginLandingPageGraphQLPlayground,
} from 'apollo-server-core';
import {ApolloServer} from 'apollo-server-express';
import {ApolloServer, UserInputError} from 'apollo-server-express';
import {NextFunction, Request, Response} from 'express';
import ExpressPinoLogger from 'express-pino-logger';
import {execute, GraphQLSchema, subscribe} from 'graphql';
import {set} from 'lodash';
Expand Down Expand Up @@ -184,7 +185,7 @@ export class GraphqlModule implements OnModuleInit, OnModuleDestroy {
}

app.use(ExpressPinoLogger(PinoConfig));

app.use(limitBatchedQueries);
await server.start();
server.applyMiddleware({
app,
Expand All @@ -194,3 +195,21 @@ export class GraphqlModule implements OnModuleInit, OnModuleDestroy {
return server;
}
}
function limitBatchedQueries(req: Request, res: Response, next: NextFunction): void {
const errors = [];
if (argv['query-batch-limit'] && argv['query-batch-limit'] > 0) {
if (req.method === 'POST') {
try {
const queries = req.body;
if (Array.isArray(queries) && queries.length > argv['query-batch-limit']) {
errors.push(new UserInputError('Batch query limit exceeded'));
throw errors;
}
} catch (error) {
res.status(500).json({errors: [...error]});
return next(error);
}
}
}
next();
}
5 changes: 5 additions & 0 deletions packages/query/src/yargs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ export function getYargsOption() {
type: 'number',
default: 100,
},
'query-batch-limit': {
demandOption: false,
describe: 'Set limit on number on the maximum batch queries',
type: 'number',
},
'query-depth-limit': {
demandOption: false,
describe: 'Set limit on query depth',
Expand Down

0 comments on commit 179d9a8

Please sign in to comment.