{"_id":"@500px_info/graphql-query-complexity","_rev":"1-24cd167989dcd33703797f3e289338de","name":"@500px_info/graphql-query-complexity","dist-tags":{"latest":"0.4.2-rc1"},"versions":{"0.4.2-rc1":{"name":"@500px_info/graphql-query-complexity","version":"0.4.2-rc1","description":"Validation rule for GraphQL query complexity analysis","main":"dist/index.js","types":"dist/index.d.ts","scripts":{"lint":"eslint src/**/*.ts","clean":"rimraf dist/*","build":"tsc","test":"npm run lint && npm run testonly","testonly":"mocha --check-leaks --exit --full-trace --require ts-node/register 'src/**/__tests__/**/*-test.{ts,tsx}'","dist":"npm run clean && tsc && npm run build","prepublish":"npm run clean && npm run dist"},"dependencies":{"lodash.get":"^4.4.2"},"peerDependencies":{"graphql":"^0.13.0 || ^14.0.0"},"repository":{"type":"git","url":"https://github.com/slicknode/graphql-query-complexity.git"},"keywords":["graphql","query","validation","cost","complexity","analysis"],"author":{"name":"Ivo Meißner"},"license":"MIT","devDependencies":{"@types/assert":"^0.0.31","@types/chai":"^4.1.4","@types/graphql":"^0.13.0 || ^14.0.0","@types/lodash.get":"^4.4.4","@types/mocha":"^5.2.5","chai":"^4.1.0","eslint":"^5.4.0","eslint-plugin-typescript":"^0.12.0","graphql":"^0.13.0 || ^14.0.0","mocha":"^5.2.0","rimraf":"^2.6.1","ts-node":"^7.0.1","typescript":"^3.0.1","typescript-eslint-parser":"^18.0.0"},"licenseText":"MIT License\n\nCopyright (c) 2017 Ivo Meißner\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","_id":"@500px_info/graphql-query-complexity@0.4.2-rc1","dist":{"shasum":"7f33d901ea837d735810df54b634435ebf7949b0","integrity":"sha512-lWXiE5pxhIkv5o/l6N1MjzFujT2FMMb1sZNQtUVVIgGF3Hd2BIFOl07Piw+gj1XcQSBkbX6wzGHmQRqbWus5rw==","tarball":"https://registry.npmjs.org/@500px_info/graphql-query-complexity/-/graphql-query-complexity-0.4.2-rc1.tgz","fileCount":83,"unpackedSize":167949,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeIM4QCRA9TVsSAnZWagAAizIP/2Vd/teDMyPw55p7fsV6\nQTOncZZRb3okXCgJ324kQfxbhf9t19JN9IRhEdc+XaTu452tZTfFG3sb3fpM\nxsRUR4E9PPZ+BHPgQUmNpdsIa++9N4ojZgZg5+11LqrpPKq+2gn8bwor3A+k\n87XYh8hGIuNFpWojgSi63TX5yvxD8rF5bX1dlwqu8EFf0Y643ddyqFjfMUqU\njyb7aNFRmfMiHufXc0A/JW+5hGJ02vV3CQeBTNWgZBQ+crDO3U3+vearz8kX\nPpfLT1mvc1MncGhp6kF3lzx2gQoIdpoEgNjIY1/YtisjY9L8MuuRoGU7ZkDl\niLIzSV8bezv40RU7q9pFl92EfuEHCpHvVNguiGhsMoYk4/E5u82H/m5doxNA\nGbndk8C+toIrjBWqbkiih/qQUoTyLDArgXcEA0p9jrg6QyRxib0l8QmoV+Bc\nFCHwiIHahKM1ILzeg9BU3E9lDgt2ATLFQAIEpOGm7p/TAc9xi4HmuGceWHse\nyjij9hZigo8ckVFevmfmeHBbH4xck31gGsxNSzcki68o53l9CRr8FHAnQaHp\nDI73P19vr97ornANkaY3iQO1PmY4PyFBYtLitCLXSLMazIX7lhh8654pWvTG\nnGSKc8i6XVfSzk8/uH44paKigTZPk6Wbe63ovx4i9CzhGJ1WaD5k5a2Ac9NM\nbPFQ\r\n=CPIG\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIDaJCF1H/2EcogIOL9/GwyBTgGwB95GXUA5zaPVOBQQvAiEAt5CGta/WZZn6r1Uuqsi9f45WyO+hPyyP/MpA+caIIAE="}]},"maintainers":[{"name":"500px_info","email":"platform@500px.com"}],"_npmUser":{"name":"500px_info","email":"platform@500px.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/graphql-query-complexity_0.4.2-rc1_1579208207993_0.17380851265694552"},"_hasShrinkwrap":false}},"time":{"created":"2020-01-16T20:56:47.959Z","0.4.2-rc1":"2020-01-16T20:56:48.147Z","modified":"2022-04-04T10:47:52.305Z"},"maintainers":[{"name":"500px_info","email":"platform@500px.com"}],"description":"Validation rule for GraphQL query complexity analysis","keywords":["graphql","query","validation","cost","complexity","analysis"],"repository":{"type":"git","url":"https://github.com/slicknode/graphql-query-complexity.git"},"author":{"name":"Ivo Meißner"},"license":"MIT","readme":"# GraphQL Query Complexity Analysis for graphql-js\n\n[![npm version](https://badge.fury.io/js/graphql-query-complexity.svg)](https://badge.fury.io/js/graphql-query-complexity) \n[![CircleCI](https://circleci.com/gh/slicknode/graphql-query-complexity.svg?style=shield)](https://circleci.com/gh/slicknode/graphql-query-complexity)\n\n\nThis library provides GraphQL query analysis to reject complex queries to your GraphQL server.\nThis can be used to protect your GraphQL servers against resource exhaustion and DoS attacks.\n\nWorks with [graphql-js](https://github.com/graphql/graphql-js) reference implementation. \n\n\n## Installation\n\nInstall the package via npm \n\n```bash\nnpm install -S graphql-query-complexity\n```\n\n## Usage\n\nCreate the rule with a maximum query complexity:\n\n```javascript\nimport queryComplexity, {\n  simpleEstimator\n} from 'graphql-query-complexity';\n\nconst rule = queryComplexity({\n  // The maximum allowed query complexity, queries above this threshold will be rejected\n  maximumComplexity: 1000,\n  \n  // The query variables. This is needed because the variables are not available\n  // in the visitor of the graphql-js library\n  variables: {},\n  \n  // Optional callback function to retrieve the determined query complexity\n  // Will be invoked whether the query is rejected or not\n  // This can be used for logging or to implement rate limiting\n  onComplete: (complexity: number) => {console.log('Determined query complexity: ', complexity)},\n  \n  // Optional function to create a custom error\n  createError: (max: number, actual: number) => {\n    return new GraphQLError(`Query is too complex: ${actual}. Maximum allowed complexity: ${max}`);\n  },\n  \n  // Add any number of estimators. The estimators are invoked in order, the first\n  // numeric value that is being returned by an estimator is used as the field complexity.\n  // If no estimator returns a value, an exception is raised. \n  estimators: [\n    // Add more estimators here...\n    \n    // This will assign each field a complexity of 1 if no other estimator\n    // returned a value. \n    simpleEstimator({\n      defaultComplexity: 1\n    })\n  ]\n});\n```\n\n## Configuration / Complexity Estimators\n\nThe complexity calculation of a GraphQL query can be customized with so called complexity estimators.\nA complexity estimator is a simple function that calculates the complexity for a field. You can add\nany number of complexity estimators to the rule, which are then executed one after another. \nThe first estimator that returns a numeric complexity value determines the complexity for that field. \n\nAt least one estimator has to return a complexity value, otherwise an exception is raised. You can\nfor example use the [simpleEstimator](./src/estimators/simple/README.md) as the last estimator\nin your chain to define a default value. \n\nYou can use any of the available estimators to calculate the complexity of a field\nor write your own:\n\n*   **[`simpleEstimator`](src/estimators/simple/README.md):** The simple estimator returns a fixed complexity for each field. Can be used as\n    last estimator in the chain for a default value.\n*   **[`directiveEstimator`](src/estimators/directive/README.md):** Set the complexity via a directive in your \n    schema definition (for example via GraphQL SDL)\n*   **[`fieldExtensionsEstimator`](src/estimators/fieldExtensions/README.md):** The field extensions estimator lets you set a numeric value or a custom estimator\n    function in the field config extensions of your schema. \n*   **[`fieldConfigEstimator`](src/estimators/fieldConfig/README.md):** (DEPRECATED) The field config estimator lets you set a numeric value or a custom estimator\n    function in the field config of your schema. \n*   **[`legacyEstimator`](src/estimators/legacy/README.md):** (DEPRECATED) The legacy estimator implements the logic of previous versions. Can be used\n    to gradually migrate your codebase to new estimators. \n*   PRs welcome...\n\nConsult the documentation of each estimator for information about how to use them. \n\n## Creating Custom Estimators\n\nAn estimator has the following function signature: \n\n```typescript\ntype ComplexityEstimatorArgs = {\n  // The composite type (interface, object, union) that the evaluated field belongs to\n  type: GraphQLCompositeType,\n  \n  // The GraphQLField that is being evaluated\n  field: GraphQLField<any, any>,\n  \n  // The input arguments of the field\n  args: {[key: string]: any},\n  \n  // The complexity of all child selections for that field\n  childComplexity: number\n}\n\ntype ComplexityEstimator = (options: ComplexityEstimatorArgs) => number | void;\n```\n\n\n## Usage with express-graphql\n\nTo use the query complexity analysis validation rule with express-graphql, use something like the\nfollowing: \n\n```javascript\nimport queryComplexity from 'graphql-query-complexity';\nimport express from 'express';\nimport graphqlHTTP from 'express-graphql';\nimport schema from './schema';\n\nconst app = express();\napp.use('/api', graphqlHTTP(async (request, response, {variables}) => ({\n  schema,\n  validationRules: [ queryComplexity({\n    maximumComplexity: 1000,\n    variables,\n    onComplete: (complexity: number) => {console.log('Query Complexity:', complexity);},\n  }) ]\n})));\n```\n\n## Calculate query complexity\n\nIf you want to calculate the complexity of a GraphQL query outside of the validation phase, for example to\nreturn the complexity value in a resolver, you can calculate the complexity via `getComplexity`:\n\n```javascript\nimport { getComplexity, simpleEstimator } from 'graphql-query-complexity';\nimport { parse } from 'graphql';\n\n// Import your schema or get it form the info object in your resolver\nimport schema from './schema';\n\n// You can also use gql template tag to get the parsed query\nconst query = parse(`\n  query Q($count: Int) {\n    some_value\n    some_list(count: $count) {\n      some_child_value\n    }\n  }\n`);\n\nconst complexity = getComplexity({\n  estimators: [\n    simpleEstimator({defaultComplexity: 1})\n  ],\n  schema,\n  query,\n  variables: {\n    count: 10,\n  },\n});\n\nconsole.log(complexity); // Output: 3\n```\n\n\n## Prior Art\n\nThis project is inspired by the following prior projects: \n\n-   Query complexity analysis in the [Sangria GraphQL](http://sangria-graphql.org/) implementation.\n-   [graphql-cost-analysis](https://github.com/pa-bru/graphql-cost-analysis) - Multipliers and directiveEstimator\n","readmeFilename":"README.md"}