Apollo Server Query Complexity Plugin

4.0.0 · active · verified Tue Apr 21

The `apollo-server-plugin-query-complexity` package provides a plugin for `@apollo/server` to enforce query complexity limits, safeguarding against overly resource-intensive queries. It is currently at version 4.0.0, aligning with `@apollo/server` v4.x. This plugin differentiates itself by being fully compatible with GraphQL operation variables, a feature that standard `graphql-js` validation rules cannot directly access when integrated with Apollo Server. It leverages `graphql-query-complexity` for its core estimation logic, supporting various estimators like `directiveEstimator` and `simpleEstimator`, which allow developers to define complexity values directly within their schema or through default calculation rules. This mechanism is crucial for preventing denial-of-service attacks by ensuring server stability and fair resource allocation. The project appears actively maintained, with releases typically synchronized with major `@apollo/server` versions.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to integrate the query complexity plugin into an Apollo Server instance with directive-based and simple complexity estimators, setting a maximum complexity limit.

import { ApolloServer } from '@apollo/server';
import ApolloServerPluginQueryComplexity from 'apollo-server-plugin-query-complexity';
import { directiveEstimator, simpleEstimator } from 'graphql-query-complexity';

const typeDefs = `#graphql
  directive @complexity(
    value: Int!
    multipliers: [String!]
  ) on FIELD_DEFINITION

  type Query {
    a: String! # Complexity of 1
    b(n: Int!): String! @complexity(value: 1, multipliers: ["n"]) # Complexity of variable "n"
  }
`;

const server = new ApolloServer({
  typeDefs,
  resolvers: {},
  plugins: [
    ApolloServerPluginQueryComplexity({
      estimators: [directiveEstimator(), simpleEstimator()],
      maximumComplexity: 100,
    }),
  ],
});

// Example of starting the server (assuming a basic setup, e.g., for testing)
// This part is illustrative and depends on your Apollo Server integration (e.g., Express, standalone)
async function startApolloServer() {
  // In a real application, you'd likely use startStandaloneServer or integrate with a web framework
  // For demonstration, let's just log that the server is configured
  console.log('Apollo Server configured with Query Complexity Plugin.');
  console.log('Maximum complexity set to 100.');
}

startApolloServer();

view raw JSON →