1.0.5 • Published 2 years ago

query-coster v1.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Relay style pagination aware GraphQL Query Coster

This library provides a simplified implementation of a GraphQL query cost calculator that works with the GraphQL Cursor Connections Specification.

The goal of this library is to take pagination parameters into account while calculating query cost to block database-intensive queries.

If you take the following example query where a client requests 50 Slack accounts:

query ExampleQuery {
  organization {
    SlackAccountList(first:50) {
      edges {
        cursor
        node {
          displayName
        }
      }
    }
  }
}

The query cost might grow quadratically if the API supports nested fields. These queries can be expensive for systems but aren't caught by traditional depth or complexity checks.

query ExampleQuery {
  organization {
    SlackAccountList(first:1) {
      edges {
        cursor
        node {
          displayName
        }
        associatedUsers(first: 10) {
          edges {
            cursor
            node {
              userId
            }
          }
        }
      }
    }
  }
}

Usage

This comes prebuilt as an Apollo Server plugin.

import queryCost from "query-coster";

const server = new ApolloServer({
  plugins: [
    queryCost(gqlSchema, {
      sampleRate: 1, // how many requests to take into consideration
      blockOnHighQueryCost: true, // raise an exception if a query exceeds a threshold
      costThreshold: 10_000, // cost threshold
      queryCacheSize: 1_000, // maintain an LRU cache of costs for given queries so that we don't recalculate them.
    }),
  ],
)}

Events emitted

The cost calculator emits events when it takes an action.

type Events = {
  cache_hit: () => void,
  cache_miss: () => void,
  cost_calculated: (cost: number, document: DocumentNode, durationMs: number) => void,
  error: (e: Error) => void,
  blocked_request: () => void,
}

In order to use these events, you can set up listeners.

import { emitter } from "query-coster";
emitter.on("cost_calculated", (cost: number) => console.log("Query cost", { cost }))

Development

npm run build to build.

npm run lint to lint with eslint.

npm run test to run the unit test suite with mocha.

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago