├── .gitignore ├── .npmignore ├── .travis.yml ├── LICENSE ├── README.md ├── bin └── query-validator.js ├── fixtures ├── queries │ ├── allFilms.graphql │ ├── allPeople.graphql │ └── invalid │ │ └── allFilms.graphql └── schema │ ├── dataTypes │ ├── characters │ │ ├── people.graphql │ │ └── species.graphql │ ├── film.graphql │ ├── planet.graphql │ └── ships │ │ ├── starship.graphql │ │ └── vehicle.graphql │ ├── rootQuery.graphql │ └── schema.graphql ├── package.json ├── src ├── cli.ts ├── index.ts └── test │ ├── cli.test.ts │ └── index.test.ts ├── tsconfig.json └── tslint.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Coverage directory used by tools like istanbul 7 | coverage 8 | 9 | # Dependency directory 10 | node_modules 11 | typings 12 | 13 | # build directory 14 | dist 15 | 16 | # mac directories 17 | .DS_Store 18 | 19 | # Runtime data 20 | pids 21 | *.pid 22 | *.seed 23 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | src 2 | test 3 | coverage 4 | typings 5 | fixtures 6 | npm-debug.log 7 | .bablerc 8 | .gitignore 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "6" 4 | - "5" 5 | - "4" 6 | install: 7 | - npm install 8 | - npm install graphql 9 | 10 | script: 11 | - npm test 12 | 13 | # Allow Travis tests to run in containers. 14 | sudo: false 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # graphql-validator 2 | 3 | A CLI tool to validate queries against a GraphQL Schema. The primary use case for this tool is to validate schema changes against an existing query store. 4 | 5 | ## Installation 6 | 7 | To use the validator as a command line tool 8 | 9 | ```sh 10 | npm install -g graphql @creditkarma/graphql-validator 11 | ``` 12 | 13 | To use the validator locally in a project 14 | 15 | ```sh 16 | npm install --save graphql @creditkarma/graphql-validator 17 | ``` 18 | 19 | ## Usage 20 | 21 | Given the following files 22 | 23 | schema/schema.graphql 24 | 25 | ``` 26 | schema { 27 | query: RootQuery 28 | } 29 | ``` 30 | 31 | schema/rootQuery.graphql 32 | 33 | ``` 34 | type RootQuery { 35 | testString: String 36 | } 37 | ``` 38 | 39 | queries/test.graphql 40 | 41 | ``` 42 | {testString} 43 | ``` 44 | 45 | ### Validate the query 46 | 47 | Validate the query with the following code: 48 | 49 | ```js 50 | const loadSchema = require('@creditkarma/graphql-loader') 51 | const validator = require('@creditkarma/graphql-validator') 52 | 53 | loadSchema('./schema/*.graphql', (err, schema) => { 54 | validator.validateQueryFiles('./queries/*.graphql', schema, (errors) => { 55 | if (errors) { 56 | console.log('errors', errors); 57 | } else { 58 | console.log('All queries validated'); 59 | } 60 | }) 61 | }) 62 | ``` 63 | 64 | Validate the query using promises: 65 | 66 | ```js 67 | const loadSchema = require('@creditkarma/graphql-loader') 68 | const validator = require('@creditkarma/graphql-validator') 69 | 70 | loadSchema('./schema/*.graphql').then((schema) => { 71 | validator.validateQueryFiles('./queries/*.graphql', schema).then((results) => { 72 | console.log(results) 73 | }) 74 | }) 75 | ``` 76 | 77 | Validate query using CLI tool 78 | 79 | ```sh 80 | > graphql-validator -s "./schema/**/*.graphql" "./queries/*.graphql" 81 | ``` 82 | 83 | The validator will first load and validate the schema, throwing errors if the schema isn't valid. Then it will check each query in the file glob by parsing the query and validating it against the schema. If errors are found, the will be displayed by file name and exit with exit code 1. 84 | 85 | *Note:* you must use quotes around each file glob or the utility will not work properly. 86 | 87 | ## Development 88 | 89 | Install dependencies with 90 | 91 | ```sh 92 | npm install 93 | npm run typings 94 | ``` 95 | 96 | ### Build 97 | 98 | ```sh 99 | npm run build 100 | ``` 101 | 102 | 103 | ### Run test in watch mode 104 | 105 | ```sh 106 | npm run test:watch 107 | ``` 108 | 109 | ## Contributing 110 | For more information about contributing new features and bug fixes, see our [Contribution Guidelines](https://github.com/creditkarma/CONTRIBUTING.md). 111 | External contributors must sign Contributor License Agreement (CLA) 112 | 113 | ## License 114 | This project is licensed under [Apache License Version 2.0](./LICENSE) 115 | -------------------------------------------------------------------------------- /bin/query-validator.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /* 4 | This is the CLI tool to validate scripts against a schema. It uses the API found 5 | in the src/ directory to validate all the files in the file glob CLI parameter. 6 | */ 7 | 8 | 'use strict' 9 | 10 | const program = require('commander') 11 | const packagejson = require('../package.json') 12 | const cli = require('../dist/cli') 13 | 14 | program 15 | .version(packagejson.version) 16 | .usage(`[options] ()`) 17 | .option('-s, --schema [pattern]', 'Use a file glob that defines a complete schema to validate against', '') 18 | .parse(process.argv) 19 | 20 | if (!program.args.length || !program.schema) { 21 | program.outputHelp() 22 | } else { 23 | cli.loadSchema(program.schema) 24 | .then((schema) => cli.validateQueries(program.args[0], schema)) 25 | .catch((err) => process.exit(1)) 26 | } 27 | -------------------------------------------------------------------------------- /fixtures/queries/allFilms.graphql: -------------------------------------------------------------------------------- 1 | {allFilms{title}} 2 | -------------------------------------------------------------------------------- /fixtures/queries/allPeople.graphql: -------------------------------------------------------------------------------- 1 | {allPeople{name}} 2 | -------------------------------------------------------------------------------- /fixtures/queries/invalid/allFilms.graphql: -------------------------------------------------------------------------------- 1 | {allFilms{titles names}} 2 | -------------------------------------------------------------------------------- /fixtures/schema/dataTypes/characters/people.graphql: -------------------------------------------------------------------------------- 1 | type Person implements Node { 2 | name: String 3 | birthYear: String 4 | eyeColor: String 5 | gender: String 6 | hairColor: String 7 | height: Int 8 | mass: Int 9 | skinColor: String 10 | homeworld: Planet 11 | films: [Film] 12 | species: [Species] 13 | starships: [Starship] 14 | vehicles: [Vehicle] 15 | created: String 16 | edited: String 17 | id: ID! 18 | } 19 | -------------------------------------------------------------------------------- /fixtures/schema/dataTypes/characters/species.graphql: -------------------------------------------------------------------------------- 1 | type Species implements Node { 2 | name: String 3 | classification: String 4 | designation: String 5 | averageHeight: Float 6 | averageLifespan: Int 7 | eyeColors: [String] 8 | hairColors: [String] 9 | skinColors: [String] 10 | language: String 11 | homeworld: Planet 12 | people: [Person] 13 | films: [Film] 14 | created: String 15 | edited: String 16 | id: ID! 17 | } 18 | -------------------------------------------------------------------------------- /fixtures/schema/dataTypes/film.graphql: -------------------------------------------------------------------------------- 1 | type Film implements Node { 2 | title: String 3 | episodeID: Int 4 | openingCrawl: String 5 | director: String 6 | producers: [String] 7 | releaseDate: String 8 | species: [Species] 9 | starships: [Starship] 10 | vehicles: [Vehicle] 11 | characters: [Person] 12 | planets: [Planet] 13 | created: String 14 | edited: String 15 | id: ID! 16 | } 17 | -------------------------------------------------------------------------------- /fixtures/schema/dataTypes/planet.graphql: -------------------------------------------------------------------------------- 1 | type Planet implements Node { 2 | name: String 3 | diameter: Int 4 | rotationPeriod: Int 5 | orbitalPeriod: Int 6 | gravity: String 7 | population: Int 8 | climates: [String] 9 | terrains: [String] 10 | surfaceWater: Float 11 | residents: [Person] 12 | films: [Film] 13 | created: String 14 | edited: String 15 | id: ID! 16 | } 17 | -------------------------------------------------------------------------------- /fixtures/schema/dataTypes/ships/starship.graphql: -------------------------------------------------------------------------------- 1 | type Starship implements Node { 2 | name: String 3 | model: String 4 | starshipClass: String 5 | manufacturers: [String] 6 | costInCredits: Float 7 | length: Float 8 | crew: String 9 | passengers: String 10 | maxAtmospheringSpeed: Int 11 | hyperdriveRating: Float 12 | MGLT: Int 13 | cargoCapacity: Float 14 | consumables: String 15 | pilots: [Person] 16 | films: [Film] 17 | created: String 18 | edited: String 19 | id: ID! 20 | } 21 | -------------------------------------------------------------------------------- /fixtures/schema/dataTypes/ships/vehicle.graphql: -------------------------------------------------------------------------------- 1 | type Vehicle implements Node { 2 | name: String 3 | model: String 4 | vehicleClass: String 5 | manufacturers: [String] 6 | costInCredits: Int 7 | length: Float 8 | crew: String 9 | passengers: String 10 | maxAtmospheringSpeed: Int 11 | cargoCapacity: Int 12 | consumables: String 13 | pilots: [Person] 14 | films: [Film] 15 | created: String 16 | edited: String 17 | id: ID! 18 | } 19 | -------------------------------------------------------------------------------- /fixtures/schema/rootQuery.graphql: -------------------------------------------------------------------------------- 1 | interface Node { 2 | id: ID! 3 | } 4 | 5 | type RootQuery { 6 | allFilms(offset: Int, limit: Int): [Film] 7 | film(id: ID, filmID: ID): Film 8 | allPeople(offset: Int, limit: Int): [Person] 9 | person(id: ID, personID: ID): Person 10 | allPlanets(offset: Int, limit: Int): [Planet] 11 | planet(id: ID, planetID: ID): Planet 12 | allSpecies(offset: Int, limit: Int): [Species] 13 | species(id: ID, speciesID: ID): Species 14 | allStarships(offset: Int, limit: Int): [Starship] 15 | starship(id: ID, starshipID: ID): Starship 16 | allVehicles(offset: Int, limit: Int): [Vehicle] 17 | vehicle(id: ID, vehicleID: ID): Vehicle 18 | node(id: ID!): Node 19 | } 20 | -------------------------------------------------------------------------------- /fixtures/schema/schema.graphql: -------------------------------------------------------------------------------- 1 | schema { 2 | query: RootQuery 3 | } 4 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@creditkarma/graphql-validator", 3 | "version": "0.5.0", 4 | "description": "Validate queries agains a GraphQL Schema", 5 | "repository": { 6 | "url": "https://github.com/creditkarma/graphql-validator" 7 | }, 8 | "main": "./dist/index.js", 9 | "scripts": { 10 | "clean": "rimraf coverage/ dist/ node_modules/", 11 | "build": "tsc", 12 | "build:watch": "tsc --watch", 13 | "lint": "tslint src/**/*", 14 | "pretest": "npm run build", 15 | "test": "npm run test:only --", 16 | "test:watch": "npm test -- -w", 17 | "test:only": "lab -c -S ./dist/test", 18 | "coverage": "lab -c -S -r console -o stdout -r html -o ./coverage/coverage.html ./dist/test", 19 | "release:patch": "npm version patch && npm run release:publish", 20 | "release:minor": "npm version minor && npm run release:publish", 21 | "release:major": "npm version major && npm run release:publish", 22 | "release:publish": "npm publish && git push --follow-tags" 23 | }, 24 | "bin": { 25 | "graphql-validator": "./bin/query-validator.js" 26 | }, 27 | "keywords": [ 28 | "GraphQL" 29 | ], 30 | "author": "Credit Karma", 31 | "license": "Apache-2.0", 32 | "devDependencies": { 33 | "@types/code": "^4.0.0", 34 | "@types/glob": "^5.0.30", 35 | "@types/graphql": "^0.9.0", 36 | "@types/lab": "^11.1.0", 37 | "@types/mkdirp": "^0.5.0", 38 | "@types/node": "^8.0.0", 39 | "@types/rimraf": "0.0.28", 40 | "code": "^4.0.0", 41 | "lab": "^14.1.0", 42 | "mkdirp": "^0.5.1", 43 | "rimraf": "^2.6.1", 44 | "tslint": "^5.5.0", 45 | "typescript": "^2.4.1" 46 | }, 47 | "dependencies": { 48 | "@creditkarma/graphql-loader": "^0.6.3", 49 | "commander": "^2.11.0", 50 | "glob": "^7.1.2", 51 | "graphql-tools": "^1.1.0" 52 | }, 53 | "peerDependencies": { 54 | "graphql": "^0.9.0 || ^0.10.1" 55 | }, 56 | "typescript": { 57 | "definition": "dist/index.d.ts" 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/cli.ts: -------------------------------------------------------------------------------- 1 | import * as loader from '@creditkarma/graphql-loader' 2 | import * as validator from './index' 3 | 4 | export function loadSchema(schemaPattern: string): Promise { 5 | return new Promise((resolve, reject) => { 6 | console.log(`\nLoading schema from ${schemaPattern}`) 7 | loader.loadSchema(schemaPattern) 8 | .then((schema) => { 9 | console.log('valid schema loaded...') 10 | resolve(schema) 11 | }) 12 | .catch((errs) => { 13 | console.log(`${errs.toString()}\n`) 14 | reject(errs) 15 | }) 16 | }) 17 | } 18 | 19 | export function validateQueries(queriesPattern: string, validSchema: loader.GraphQLSchema): Promise { 20 | return new Promise((resolve, reject) => { 21 | console.log(`\nValidating queries for ${queriesPattern} using loaded schema`) 22 | 23 | function outputErrors(errs) { 24 | console.log('\nErrors found:') 25 | errs.forEach((err) => { 26 | console.log(`\nFile: ${err.file}`) 27 | err.errors.forEach((errStr) => { 28 | console.log(`\t${errStr}`) 29 | }) 30 | }) 31 | console.log('\n') 32 | } 33 | 34 | validator.validateQueryFiles(queriesPattern, validSchema).then(() => { 35 | console.log('All queries are valid\n') 36 | resolve() 37 | }).catch((errs) => { 38 | outputErrors(errs) 39 | reject(errs) 40 | }) 41 | }) 42 | } 43 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs' 2 | import * as globUtil from 'glob' 3 | import { DocumentNode, GraphQLError, GraphQLSchema, parse, validate } from 'graphql' 4 | 5 | export interface IQueryFileError { 6 | file: string 7 | errors: string[] 8 | } 9 | 10 | export interface ILoadQueryCallback { 11 | (err, docs?: DocumentNode[]) 12 | } 13 | 14 | export interface IValidateCallback { 15 | (errors?: IQueryFileError[], results?: DocumentNode[]) 16 | } 17 | 18 | export function validateQuery(schema: GraphQLSchema, document: DocumentNode): GraphQLError[] { 19 | return validate(schema, document) 20 | } 21 | 22 | export function loadQueryFiles(glob: string | string[], callback?: ILoadQueryCallback): Promise { 23 | return new Promise((resolve, reject) => { 24 | function loadAll(files) { 25 | const promises = files.map(readFile) 26 | return Promise.all(promises) 27 | .then((fileResults) => { 28 | const docs = fileResults.map((text: string, index) => parse(text)) 29 | callback ? callback(null, docs) : resolve(docs) 30 | }) 31 | .catch((err) => callback ? callback(err) : reject(err)) 32 | } 33 | if (glob instanceof Array) { 34 | loadAll(glob) 35 | } else { 36 | readGlob(glob) 37 | .then(loadAll) 38 | .catch((err) => callback ? callback(err) : reject(err)) 39 | } 40 | }) 41 | } 42 | 43 | export function validateQueryFiles(glob: string, schema: GraphQLSchema, 44 | callback?: IValidateCallback): Promise { 45 | return new Promise((resolve, reject) => { 46 | let queries 47 | readGlob(glob) 48 | .then((files) => { 49 | queries = files 50 | return loadQueryFiles(files) 51 | }) 52 | .then((docs) => { 53 | const errors = validateQueries(docs, schema, queries) 54 | if (errors.length) { 55 | callback ? callback(errors) : reject(errors) 56 | } else { 57 | callback ? callback(null, queries) : resolve(queries) 58 | } 59 | }) 60 | .catch((err) => { 61 | const errs = [{ 62 | errors: [err.toString()], 63 | file: '', 64 | }] 65 | callback ? callback(errs) : reject(errs) 66 | }) 67 | }) 68 | } 69 | 70 | export function validateQueries(docs: DocumentNode[], schema: GraphQLSchema, files?: string[]): IQueryFileError[] { 71 | const results = [] 72 | 73 | docs.forEach((doc, index) => { 74 | const errs = validateQuery(schema, doc) 75 | 76 | if (errs.length) { 77 | results.push({ 78 | errors: errs.map((err) => err.toString()), 79 | file: files ? files[index] : '', 80 | }) 81 | } 82 | }) 83 | 84 | return results 85 | } 86 | 87 | function readGlob(pattern: string): Promise { 88 | return new Promise((resolve, reject) => { 89 | globUtil(pattern, {silent: true}, (err, files) => err ? reject(err) : resolve(files)) 90 | }) 91 | } 92 | 93 | function readFile(file: string): Promise { 94 | return new Promise((resolve, reject) => { 95 | fs.readFile(file, 'utf8', (err, data) => err ? reject(err) : resolve(data)) 96 | }) 97 | } 98 | -------------------------------------------------------------------------------- /src/test/cli.test.ts: -------------------------------------------------------------------------------- 1 | import {expect} from 'code' 2 | import * as Lab from 'lab' 3 | export const lab = Lab.script() 4 | 5 | const describe = lab.describe 6 | const it = lab.it 7 | const before = lab.before 8 | 9 | import { GraphQLLoaderError } from '@creditkarma/graphql-loader' 10 | import * as fs from 'fs' 11 | import * as graphql from 'graphql' 12 | import * as mkdirp from 'mkdirp' 13 | import * as rimraf from 'rimraf' 14 | import * as cli from '../cli' 15 | 16 | describe('GraphQL Validator CLI', () => { 17 | describe('#loadSchema', () => { 18 | describe('when loading a schema glob', () => { 19 | const glob = './fixtures/schema/**/*.graphql' 20 | let schema 21 | before((done) => { 22 | cli.loadSchema(glob).then((s) => { 23 | schema = s 24 | done() 25 | }) 26 | }) 27 | 28 | it('expect schema to be a graphql schema', (done) => { 29 | expect(schema).to.exist() 30 | expect(schema).to.be.an.instanceof(graphql.GraphQLSchema) 31 | done() 32 | }) 33 | }) 34 | 35 | describe(`when loading an invalid glob`, () => { 36 | const glob = './fixtures/not/an/existing/path' 37 | let err 38 | before((done) => { 39 | cli.loadSchema(glob).catch((e) => { 40 | err = e 41 | done() 42 | }) 43 | }) 44 | 45 | it('expect error to exist', (done) => { 46 | expect(err).to.exist() 47 | expect(err).to.be.an.instanceof(GraphQLLoaderError) 48 | done() 49 | }) 50 | }) 51 | }) 52 | 53 | describe('#validateQueries', () => { 54 | let schema: graphql.GraphQLSchema 55 | before(() => cli.loadSchema('./fixtures/schema/**/*.graphql').then((r) => schema = r)) 56 | 57 | describe('when validating a query glob', () => { 58 | let results 59 | let glob = './fixtures/queries/*.graphql' 60 | before((done) => { 61 | cli.validateQueries(glob, schema).then((r) => { 62 | results = r 63 | done() 64 | }) 65 | }) 66 | 67 | it('expect results to be empty', (done) => { 68 | expect(results).to.be.undefined() 69 | done() 70 | }) 71 | }) 72 | 73 | describe('when validating a query glob with invalid queries', () => { 74 | let errs 75 | let glob = './fixtures/queries/**/*.graphql' 76 | before((done) => { 77 | cli.validateQueries(glob, schema).catch((e) => { 78 | errs = e 79 | done() 80 | }) 81 | }) 82 | 83 | it('expect validation results to exist', (done) => { 84 | expect(errs).to.be.an.array() 85 | expect(errs.length).to.equal(1) 86 | done() 87 | }) 88 | }) 89 | 90 | describe('when validating a glob with unreadable files', () => { 91 | const root = './fixtures/queries/unreadable' 92 | const glob = `${root}/*.graphql` 93 | let errs 94 | before((done) => { 95 | mkdirp(root, () => { 96 | fs.writeFile(`${root}/operation.graphql`, 'hello', {mode: '333'}, (err) => { 97 | cli.validateQueries(glob, schema).catch((e) => { 98 | errs = e 99 | rimraf(root, done) 100 | }) 101 | }) 102 | }) 103 | }) 104 | 105 | it('expect error to exist', (done) => { 106 | expect(errs).to.exist() 107 | expect(errs.length).to.equal(1) 108 | done() 109 | }) 110 | }) 111 | }) 112 | }) 113 | -------------------------------------------------------------------------------- /src/test/index.test.ts: -------------------------------------------------------------------------------- 1 | import {expect} from 'code' 2 | import * as Lab from 'lab' 3 | export const lab = Lab.script() 4 | 5 | const describe = lab.describe 6 | const it = lab.it 7 | const before = lab.before 8 | 9 | import { loadSchema } from '@creditkarma/graphql-loader' 10 | import * as fs from 'fs' 11 | import * as glob from 'glob' 12 | import * as graphql from 'graphql' 13 | import * as mkdirp from 'mkdirp' 14 | import * as rimraf from 'rimraf' 15 | import * as validator from '../index' 16 | 17 | describe('GraphQL Validator', () => { 18 | let schema: graphql.GraphQLSchema 19 | before(() => loadSchema('./fixtures/schema/**/*.graphql').then((r) => schema = r)) 20 | 21 | describe('when validating a valid query', () => { 22 | let results 23 | before((done) => { 24 | const query = graphql.parse(`{allPeople{name}}`) 25 | results = validator.validateQuery(schema, query) 26 | done() 27 | }) 28 | 29 | it('expect results to be an empty array', (done) => { 30 | expect(results).to.exist() 31 | expect(results.length).to.equal(0) 32 | done() 33 | }) 34 | }) 35 | 36 | describe('when validating a invalid query', () => { 37 | let results 38 | before((done) => { 39 | const query = graphql.parse(`{allPeople{anInvalidFieldName}}`) 40 | results = validator.validateQuery(schema, query) 41 | done() 42 | }) 43 | 44 | it('expect errors to exist', (done) => { 45 | expect(results.length).to.equal(1) 46 | expect(results[0].message).to.contain('anInvalidFieldName') 47 | done() 48 | }) 49 | }) 50 | 51 | describe('#loadQueryFiles', () => { 52 | describe('when loading a query glob', () => { 53 | const gqlGlob = './fixtures/queries/{allFilms,allPeople}.graphql' 54 | let results 55 | let cbResults 56 | before((done) => { 57 | validator.loadQueryFiles(gqlGlob).then((r) => { 58 | results = r 59 | validator.loadQueryFiles(gqlGlob, (err, cbr) => { 60 | cbResults = cbr 61 | done() 62 | }) 63 | }) 64 | }) 65 | 66 | it('expect results to be two', (done) => { 67 | expect(results.length).to.equal(2) 68 | done() 69 | }) 70 | it('expect callback results to be two', (done) => { 71 | expect(cbResults.length).to.equal(2) 72 | done() 73 | }) 74 | }) 75 | 76 | describe('when passing an invalid glob', () => { 77 | const gqlGlob = './fixtures/queries/{allFilms,allPeople}.test' 78 | let results 79 | let cbResults 80 | before((done) => { 81 | validator.loadQueryFiles(gqlGlob).then((r) => { 82 | results = r 83 | validator.loadQueryFiles(gqlGlob, (err, cbr) => { 84 | cbResults = cbr 85 | done() 86 | }) 87 | }) 88 | }) 89 | 90 | it('expect results to empty', (done) => { 91 | expect(results.length).to.exist() 92 | done() 93 | }) 94 | it('expect callback results to empty', (done) => { 95 | expect(cbResults.length).to.exist() 96 | done() 97 | }) 98 | }) 99 | 100 | describe('when accessing inaccessable path in glob', () => { 101 | const root = './fixtures/test' 102 | const gqlGlob = `${root}/*.graphql` 103 | let results 104 | let cbResults 105 | before((done) => { 106 | mkdirp(root, '333', () => { 107 | validator.loadQueryFiles(gqlGlob).catch((r) => { 108 | results = r 109 | validator.loadQueryFiles(gqlGlob, (cbr) => { 110 | cbResults = cbr 111 | rimraf(root, done) 112 | }) 113 | }) 114 | }) 115 | }) 116 | 117 | it('expect error to exist', (done) => { 118 | expect(results).to.exist() 119 | done() 120 | }) 121 | it('expect callback error to exist', (done) => { 122 | expect(cbResults).to.exist() 123 | done() 124 | }) 125 | }) 126 | 127 | describe('when accessing unreadable file in glob', () => { 128 | const root = './fixtures/queries/unreadable' 129 | const gqlGlob = `${root}/*.graphql` 130 | let results 131 | let cbResults 132 | before((done) => { 133 | mkdirp(root, () => { 134 | fs.writeFile(`${root}/operation.graphql`, 'hello', {mode: 333}, (err) => { 135 | validator.loadQueryFiles(gqlGlob).catch((r) => { 136 | results = r 137 | validator.loadQueryFiles(gqlGlob, (cbr) => { 138 | cbResults = cbr 139 | rimraf(root, done) 140 | }) 141 | }) 142 | }) 143 | }) 144 | }) 145 | 146 | it('expect error to exist', (done) => { 147 | expect(results).to.exist() 148 | done() 149 | }) 150 | it('expect callback error to exist', (done) => { 151 | expect(cbResults).to.exist() 152 | done() 153 | }) 154 | }) 155 | 156 | describe('when loading a query file array', () => { 157 | let results 158 | let fileNames 159 | let cbResults 160 | before((done) => { 161 | glob('./fixtures/queries/*.graphql', (_, files) => { 162 | fileNames = files 163 | validator.loadQueryFiles(files).then((r) => { 164 | results = r 165 | validator.loadQueryFiles(files, (err, cbr) => { 166 | cbResults = cbr 167 | done() 168 | }) 169 | }) 170 | }) 171 | }) 172 | 173 | it('should load one query per file', (done) => { 174 | expect(results.length).to.equal(fileNames.length) 175 | done() 176 | }) 177 | it('should load one query per file by callback', (done) => { 178 | expect(cbResults.length).to.equal(fileNames.length) 179 | done() 180 | }) 181 | }) 182 | }) 183 | 184 | describe('#validateQueryFiles', () => { 185 | describe('when validating a query array', () => { 186 | let results 187 | before(() => { 188 | return validator.loadQueryFiles('./fixtures/queries/*.graphql').then((queries) => { 189 | results = validator.validateQueries(queries, schema) 190 | }) 191 | }) 192 | 193 | it('expect results to be emtpy', (done) => { 194 | expect(results.length).to.equal(0) 195 | done() 196 | }) 197 | }) 198 | 199 | describe('when validating a query array with invalid queries', () => { 200 | let results 201 | before(() => { 202 | return validator.loadQueryFiles('./fixtures/queries/**/*.graphql').then((queries) => { 203 | results = validator.validateQueries(queries, schema) 204 | }) 205 | }) 206 | 207 | it('expect results to be equal 1', (done) => { 208 | expect(results.length).to.equal(1) 209 | done() 210 | }) 211 | }) 212 | 213 | describe('when validating a query glob', () => { 214 | const gqlGlob = './fixtures/queries/*.graphql' 215 | let results 216 | let cbResults 217 | before((done) => { 218 | validator.validateQueryFiles(gqlGlob, schema).then((r) => { 219 | results = r 220 | validator.validateQueryFiles(gqlGlob, schema, (err, cbr) => { 221 | cbResults = cbr 222 | done() 223 | }) 224 | }) 225 | }) 226 | 227 | it('expect results to be empty', (done) => { 228 | expect(results).to.be.instanceOf(Array) 229 | .and.to.have.length(2) 230 | .and.to.contain('./fixtures/queries/allFilms.graphql') 231 | .and.to.contain('./fixtures/queries/allPeople.graphql') 232 | done() 233 | }) 234 | it('expect callback results to be empty', (done) => { 235 | expect(cbResults).to.be.instanceOf(Array) 236 | .and.to.have.length(2) 237 | .and.to.contain('./fixtures/queries/allFilms.graphql') 238 | .and.to.contain('./fixtures/queries/allPeople.graphql') 239 | done() 240 | }) 241 | }) 242 | 243 | describe('when validating a query glob with invalid queries', () => { 244 | const gqlGlob = './fixtures/queries/**/*.graphql' 245 | let results 246 | let cbResults 247 | before((done) => { 248 | validator.validateQueryFiles(gqlGlob, schema).catch((r) => { 249 | results = r 250 | validator.validateQueryFiles(gqlGlob, schema, (err, cbr) => { 251 | cbResults = cbr 252 | done() 253 | }) 254 | }) 255 | }) 256 | 257 | it('expect validation results to exist', (done) => { 258 | expect(results).to.be.an.array() 259 | expect(results.length).to.equal(1) 260 | done() 261 | }) 262 | }) 263 | 264 | describe('when validating a glob with unreadable files', () => { 265 | const root = './fixtures/queries/unreadable' 266 | const gqlGlob = `${root}/*.graphql` 267 | let results 268 | let cbResults 269 | before((done) => { 270 | mkdirp(root, () => { 271 | fs.writeFile(`${root}/operation.graphql`, 'hello', {mode: '333'}, (err) => { 272 | validator.validateQueryFiles(gqlGlob, schema).catch((r) => { 273 | results = r 274 | validator.validateQueryFiles(gqlGlob, schema, (cbr) => { 275 | cbResults = cbr 276 | rimraf(root, done) 277 | }) 278 | }) 279 | }) 280 | }) 281 | }) 282 | 283 | it('expect error to exist', (done) => { 284 | expect(results).to.exist() 285 | done() 286 | }) 287 | it('expect callback error to exist', (done) => { 288 | expect(cbResults).to.exist() 289 | done() 290 | }) 291 | }) 292 | 293 | }) 294 | }) 295 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "module": "commonjs", 5 | "moduleResolution": "node", 6 | "sourceMap": true, 7 | "declaration": true, 8 | "noImplicitAny": false, 9 | "rootDir": "./src", 10 | "outDir": "./dist", 11 | "allowSyntheticDefaultImports": true, 12 | "pretty": true, 13 | "removeComments": true, 14 | "types": [ 15 | "@types/graphql", 16 | "@types/node" 17 | ] 18 | }, 19 | "exclude": [ 20 | "node_modules", 21 | "dist", 22 | "bin" 23 | ] 24 | } 25 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rules": { 4 | "no-console": false, 5 | "semicolon": [ 6 | true, 7 | "never" 8 | ], 9 | "quotemark": [ 10 | true, 11 | "single", 12 | "avoid-escape" 13 | ] 14 | } 15 | } 16 | --------------------------------------------------------------------------------