This library offers a means to calculate the cost of a query, facilitating rate limiting similar to the Github GraphQL API.
NOTE: Currently, it's only compatible with schemas adhering to GraphQL Cursor Connections Specification.
You can install the package using either npm or yarn.
npm install graphql-cost-calculator
yarn add graphql-cost-calculator
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 }
- MaxNode: This represents the estimated maximum node count.
- Cost: The computed cost. For more on this concept, refer to the Github document.
{
schema: GraphQLSchema;
query: string;
variables?: Record<string, any>;
typeCostMap?: Record<string, number>;
}
This lets you assign an additional weight to specific object types. If your query contains these specified object types, the cost calculator will append their respective weights.
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 }