Skip to content

Add a context option for passing the request context to estimators #77

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

Merged
merged 2 commits into from
Aug 27, 2022
Merged
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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ const rule = createComplexityRule({
// in the visitor of the graphql-js library
variables: {},

// The context object for the request (optional)
context: {}

// specify operation name only when pass multi-operation documents
operationName?: string,

Expand Down Expand Up @@ -110,6 +113,9 @@ type ComplexityEstimatorArgs = {

// The complexity of all child selections for that field
childComplexity: number;

// The context object for the request if it was provided
context?: Record<string, any>;
};

type ComplexityEstimator = (options: ComplexityEstimatorArgs) => number | void;
Expand Down
9 changes: 9 additions & 0 deletions src/QueryComplexity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export type ComplexityEstimatorArgs = {
node: FieldNode;
args: { [key: string]: any };
childComplexity: number;
context?: Record<string, any>;
};

export type ComplexityEstimator = (
Expand Down Expand Up @@ -78,6 +79,9 @@ export interface QueryComplexityOptions {

// An array of complexity estimators to use for estimating the complexity
estimators: Array<ComplexityEstimator>;

// Pass request context to the estimators via estimationContext
context?: Record<string, any>;
}

function queryComplexityMessage(max: number, actual: number): string {
Expand All @@ -93,6 +97,7 @@ export function getComplexity(options: {
query: DocumentNode;
variables?: Record<string, any>;
operationName?: string;
context?: Record<string, any>;
}): number {
const typeInfo = new TypeInfo(options.schema);

Expand All @@ -109,6 +114,7 @@ export function getComplexity(options: {
estimators: options.estimators,
variables: options.variables,
operationName: options.operationName,
context: options.context,
});

visit(options.query, visitWithTypeInfo(typeInfo, visitor));
Expand All @@ -130,6 +136,7 @@ export default class QueryComplexity {
includeDirectiveDef: GraphQLDirective;
skipDirectiveDef: GraphQLDirective;
variableValues: Record<string, any>;
requestContext?: Record<string, any>;

constructor(context: ValidationContext, options: QueryComplexityOptions) {
if (
Expand All @@ -149,6 +156,7 @@ export default class QueryComplexity {
this.skipDirectiveDef = this.context.getSchema().getDirective('skip');
this.estimators = options.estimators;
this.variableValues = {};
this.requestContext = options.context;

this.OperationDefinition = {
enter: this.onOperationDefinitionEnter,
Expand Down Expand Up @@ -327,6 +335,7 @@ export default class QueryComplexity {
field,
node: childNode,
type: typeDef,
context: this.requestContext,
};
const validScore = this.estimators.find((estimator) => {
const tmpComplexity = estimator(estimatorArgs);
Expand Down
34 changes: 31 additions & 3 deletions src/__tests__/QueryComplexity-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -639,7 +639,7 @@ describe('QueryComplexity analysis', () => {
...on Union {
...on Item {
complexScalar1: complexScalar
}
}
}
...on SecondItem {
scalar
Expand Down Expand Up @@ -678,7 +678,7 @@ describe('QueryComplexity analysis', () => {
fragment F on Union {
...on Item {
complexScalar1: complexScalar
}
}
}
`);

Expand Down Expand Up @@ -759,7 +759,7 @@ describe('QueryComplexity analysis', () => {
}
}
}

fragment F on Query {
complexScalar
...on Query {
Expand Down Expand Up @@ -832,4 +832,32 @@ describe('QueryComplexity analysis', () => {
}),
]);
});

it('passed context to estimators', () => {
const ast = parse(`
query {
scalar
requiredArgs(count: 10) {
scalar
}
}
`);

const contextEstimator: ComplexityEstimator = ({
context,
childComplexity,
}) => {
return context['complexityMultiplier'] * (childComplexity || 1);
};

const complexity = getComplexity({
estimators: [contextEstimator],
schema,
query: ast,
context: { complexityMultiplier: 5 },
});

// query.scalar(5) + query.requiredArgs(5) * requiredArgs.scalar(5)
expect(complexity).to.equal(30);
});
});
8 changes: 3 additions & 5 deletions src/__tests__/utils/compatResolveType.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { GraphQLType } from 'graphql';

import graphqlPackage from 'graphql/package.json';
import * as graphql from 'graphql';
import semver from 'semver';

/**
Expand All @@ -10,8 +8,8 @@ import semver from 'semver';
* @param type
* @returns
*/
export function compatResolveType(type: GraphQLType): any {
if (semver.gte(graphqlPackage.version, '16.0.0')) {
export function compatResolveType(type: graphql.GraphQLType): any {
if (graphql.version && semver.gte(graphql.version, '16.0.0')) {
return () => type.toString();
} else {
return () => type;
Expand Down