# smartgraphql

> GraphQL Query Cost & Depth Complexity Analysis

Latest version **1.0.1** (published 2018-10-23) · ISC license · 0 weekly downloads

## Install

```sh
npm install smartgraphql
pnpm add smartgraphql
yarn add smartgraphql
bun add smartgraphql
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.1 |
| Published | 2018-10-23 |
| First published | 2018-10-23 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 5 |
| Unpacked size | 25.7 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 6 |
| Author | Seth, Mark, Julia, Manjeet |
| Maintainers | smartgraphql |
| Keywords | depth, cost, security, graphql, server, resources, complexity |

## Links

- npm: https://www.npmjs.com/package/smartgraphql
- Repository: https://github.com/smartGraphQL/PROgraphQL
- Homepage: https://github.com/smartGraphQL/PROgraphQL#readme
- Issues: https://github.com/smartGraphQL/PROgraphQL/issues
- npm.io page: https://npm.io/package/smartgraphql

## Dependencies (5)

- [express](https://npm.io/package/express.md) ^4.16.3
- [graphql](https://npm.io/package/graphql.md) ^0.13.2
- [nodemon](https://npm.io/package/nodemon.md) ^1.18.3
- [express-graphql](https://npm.io/package/express-graphql.md) ^0.6.12
- [babel-preset-env](https://npm.io/package/babel-preset-env.md) ^1.7.0

## Alternatives

- [apollo-link-http-common](https://npm.io/package/apollo-link-http-common.md) — 879.0K weekly downloads
- [react-relay](https://npm.io/package/react-relay.md) — 336.8K weekly downloads
- [relay-test-utils](https://npm.io/package/relay-test-utils.md) — 181.6K weekly downloads
- [@vendure/core](https://npm.io/package/@vendure/core.md) — 14.8K weekly downloads
- [@pnpm/deps.graph-sequencer](https://npm.io/package/@pnpm/deps.graph-sequencer.md) — 13.4K weekly downloads

## Recent versions

- 1.0.1 (latest) — 2018-10-23
- 1.0.0 — 2018-10-23

## README

# SmartGraphQL

![Travis (.org) branch](https://travis-ci.com/smartGraphQL/PROgraphQL.svg?branch=Distribution-Ready)


## GraphQL Query Cost & Depth Complexity Analysis

The SmartGraphQL library enables users to limit the depth and complexity of queries to their GraphQL server, preventing resource exhaustion.

Compatible with Express and Apollo-Server validation rules.

## Installation

Install this package via npm 

```
npm install -s smartgraphql 
```

## Usage

Set a limit for Cost Complexity by creating a object with the following properties:

```javascript
const ruleCost = {

  // All queries with a cost above this limit will be rejected and throw an error
  costLimit: 500,

  // Optional onSuccess method which will confirm the query has successfully passed the cost limit check with a customizable 	  message
  onSuccess: cost => `Complete, query cost is ${cost}`,

// Optional onError method to alert user that the query has been rejected with a customizable message
  onError: (cost, costLim) => `Error: Cost is ${cost} but cost limit is set to ${costLim}`,

};
```

Set a limit for query depth by creating a object with the following properties.

```javascript
const ruleDepth = {

// All queries with a depth above 'depthLimit' will be rejected and throw a GraphQLError before resolving.
  depthLimit: 100,

// Optional onSuccess method which will confirm the query has successfully passed the cost limit check with a customizable      message.
  onSuccess: depth => `Complete, query depth is ${depth}`,

// Optional onError method to alert user that the query has been rejected with a customizable GraphQLError
  onError: (depth, maximumDepth) => `Error: Current depth is ${depth} but max depth is 
	   ${maximumDepth}`,

};
```

## Depth Calculation

Depth is calculated by how nested the query is. For example the following queries are incrementally increasing:

```graphql
// ** depth = 1
query{
  Author(id:1) {
    Name
  }
}

// ** depth = 2
query{
  Author(id:1) {
    Name
    Books{
       Name
    }
  }
}

// ** depth = 3
query{
  Author(id:1) {
    Name
    Books{
      Name
      Genre{
	 Books 
  }
}
```
Inline Fragments and Fragments will not cause the query depth to increase. For example in both the following cases the query depth will remain 1: 

```graphql
//Inline Fragment
query{
  Author(id:1) {
    Name
    ... on Books{
	Pages
    }
  }
}

//Fragment
query{
  Author(id:1) {
    Name
    ...books
  }
}

fragment books on Author{
      Name
      Year
      Genre
}
```

Cyclical Queries can cause servers to crash by being nested to a large amount, and this is where setting a depth limit becomes useful. A depth limit can reject cyclical queries such as the following: 

```graphql
query{
  Artists{
    Name
    Songs{
      Name
      Artist{
        Name
        Songs{
          Name
           etc...
        }
      }
    }
  }
}
```

## Cost Calculation

Cost is calculated based on the number of times a resolve function makes a connection to the database. For example:

```graphql
query{
  artists(first: 100){
    name
    songs(first: 50){
      name
      genre{
        name
        songs(first: 10){
          name
        }
      }
    }
  }
}
```

This query would result in a cost of 5101, which can be broken down into the following steps:

- The initial request is 1 because although we’re return the first 100 artists, there will only be one connection to the database. 
- For songs we will need to connect once for each artist to get a list of their first 50 songs, so that will be 100 connections.
- For the 'songs' field inside genre, you will need to make one connection for the 5000 songs, so that will be 5000

Total Cost is 5101

## Usage with express-graphql

Integrating the rules inside the validation rules will look like this, the limit will be manadatory, but the onSuccess and onError function are optional 

```javascript
const ruleCost = {
  costLimit: 10000,
  onSuccess: cost => `Complete, query cost is ${cost}`,
  onError: (cost, costLim) => `Error: Cost is ${cost} but cost limit is set to ${costLim}`,
};

const ruleDepth = {
  depthLimit: 100,
  onSuccess: depth => `Complete, query depth is ${depth}`,
  onError: (depth, maximumDepth) => `Error: Current depth is ${depth} but max depth is ${maximumDepth}`,
};

app.use(
  '/graphql',
  graphqlHTTP(() => ({
    schema,
    graphiql: true,
    validationRules: [depthComplexity(ruleDepth), costLimit(ruleCost)],
  })),
);
```

## Credits

Developed by Julia, Manjeet, Mark & Seth

---
_Source: https://npm.io/package/smartgraphql · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
