Skip to content

Commit

Permalink
feat(harden-plugin): Allow skipping complexity check in Harden Plugin (
Browse files Browse the repository at this point in the history
  • Loading branch information
martijnvdbrug authored Feb 11, 2025
1 parent c820f42 commit 0bef00b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
10 changes: 7 additions & 3 deletions packages/harden-plugin/src/middleware/query-complexity-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,20 @@ import { HardenPluginOptions } from '../types';
export class QueryComplexityPlugin implements ApolloServerPlugin {
constructor(private options: HardenPluginOptions) {}

async requestDidStart({ schema }: GraphQLRequestContext<any>): Promise<GraphQLRequestListener<any>> {
async requestDidStart(context: GraphQLRequestContext<any>): Promise<GraphQLRequestListener<any>> {
const maxQueryComplexity = this.options.maxQueryComplexity ?? 1000;
return {
didResolveOperation: async ({ request, document }) => {
if (isAdminApi(schema)) {
if (isAdminApi(context.schema)) {
// We don't want to apply the cost analysis on the
// Admin API, since any expensive operations would require
// an authenticated session.
return;
}
if (await this.options.skip?.(context)) {
// Given skip function tells use we should not check this request for complexity
return;
}
const query = request.operationName
? separateOperations(document)[request.operationName]
: document;
Expand All @@ -41,7 +45,7 @@ export class QueryComplexityPlugin implements ApolloServerPlugin {
);
}
const complexity = getComplexity({
schema,
schema: context.schema,
query,
variables: request.variables,
estimators: this.options.queryComplexityEstimators ?? [
Expand Down
13 changes: 13 additions & 0 deletions packages/harden-plugin/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { GraphQLRequestContext } from '@apollo/server';
import { ComplexityEstimator } from 'graphql-query-complexity';

/**
Expand Down Expand Up @@ -79,4 +80,16 @@ export interface HardenPluginOptions {
* @default 'prod'
*/
apiMode?: 'dev' | 'prod';
/**
* @description
* Allows you to skip the complexity check for certain requests.
*
* @example
* ```ts
* HardenPlugin.init({
* skip: (context) => context.request.http.headers['x-storefront-ssr-auth'] === 'some-secret-token'
* }),
* ```
*/
skip?: (context: GraphQLRequestContext<any>) => Promise<boolean> | boolean;
}

0 comments on commit 0bef00b

Please sign in to comment.