0.0.1 • Published 8 months ago

graphql-cost-calculator v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

GraphQL Query Cost Calculator

This library provides query cost calculation for implemting rate limiting like Github GraphQL API.

NOTE: For now it only works for schemas that follow GraphQL Cursor Connections Specification.

Installation

Install the package via npm or yarn.

npm install graphql-cost-calculator
yarn add graphql-cost-calculator

Usage

import { calculateCost } from "graphql-cost-calculator";
import schema from "./schema"; // Import or build your schema

const result = calculateCost({
  schema,
  query: `
    query {
      viewer {
        login
        repositories(first: 100) {
          edges {
            node {
              id
  
              issues(first: 50) {
                edges {
                  node {
                    id
  
                    labels(first: 60) {
                      edges {
                        node {
                          id
                          name
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  `
})

console.log(result) // { maxNode: 305101, cost: 51 }

Result

  • MaxNode: Estimated max node count.
  • Cost: Calculated cost. (see Github document to know the concept.)

Arguments

{
  schema: GraphQLSchema;
  query: string;
  variables?: Record<string, any>;
  typeCostMap?: Record<string, number>;
}

typeCostMap

You can set an additional object type weight for some objects. When your query includes some mached object types, the cost calculator adds weight for them.

const result = calculateCost({
  schema,
  query: `
    query {
      viewer {
        login
        repositories(first: 100) {
          edges {
            node {
              id
  
              issues(first: 50) {
                edges {
                  node {
                    id
  
                    labels(first: 60) {
                      edges {
                        node {
                          id
                          name
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  `,
  typeCostMap: { RepositoryConnection: 10 }
})

// (1 + 100 + 5000 + 1000(RepositoryConnection cost) / 100 = 61
console.log(result) // { maxNode: 305101, cost: 61 }