├── .gitignore ├── .npmignore ├── .travis.yml ├── LICENSE ├── README.md ├── fixtures ├── swapi │ ├── dataTypes │ │ ├── characters │ │ │ ├── people.graphql │ │ │ └── species.graphql │ │ ├── film.graphql │ │ ├── planet.graphql │ │ └── ships │ │ │ ├── starship.graphql │ │ │ └── vehicle.graphql │ ├── rootQuery.graphql │ └── schema.graphql └── user │ └── schema.graphql ├── package.json ├── src ├── index.ts └── test │ └── index.test.ts ├── tsconfig.json └── tslint.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | .vscode 6 | 7 | # Coverage directory 8 | coverage 9 | 10 | # Dependency directory 11 | node_modules 12 | typings 13 | 14 | # build directory 15 | dist 16 | 17 | # mac directories 18 | .DS_Store 19 | 20 | # Runtime data 21 | pids 22 | *.pid 23 | *.seed 24 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | src 2 | test 3 | coverage 4 | fixtures 5 | npm-debug.log 6 | .bablerc 7 | .gitignore 8 | .vscode 9 | tsconfig.json 10 | tslint.json 11 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # graphql-loader 2 | 3 | Instantiate a GraphQL Schema by loading GraphQL Schema Language files based on a glob pattern 4 | 5 | * Allows creation of GraphQL Schema via GraphQL schema language shorthand 6 | * Supports splitting the schema into modules 7 | * Parse and validate schema files 8 | * Load GraphQL files from different modules and merge them into a single GraphQL Schema 9 | 10 | ## Installation 11 | 12 | ```sh 13 | npm install --save graphql @creditkarma/graphql-loader 14 | ``` 15 | 16 | ## Usage 17 | 18 | Given the following files 19 | 20 | schema/schema.graphql 21 | 22 | ``` 23 | schema { 24 | query: RootQuery 25 | } 26 | ``` 27 | 28 | schema/rootQuery.graphql 29 | 30 | ``` 31 | type RootQuery { 32 | testString: String 33 | } 34 | ``` 35 | 36 | ## loadSchema 37 | 38 | Given a GLOB pattern, it will load all the content of the files matching the GLOB, combine them 39 | together and return a GraphQL Schema 40 | 41 | Create a schema using promises: 42 | 43 | ```js 44 | const loader = require('@creditkarma/graphql-loader') 45 | 46 | loader.loadSchema('./schema/*.graphql').then((schema) => { 47 | console.log(schema.getQueryType().toString()) 48 | }) 49 | ``` 50 | 51 | Create a schema with a callback: 52 | 53 | ```js 54 | const loader = require('@creditkarma/graphql-loader') 55 | 56 | loader.loadSchema('./schema/*.graphql', (err, schema) => { 57 | console.log(schema.getQueryType().toString()) 58 | }) 59 | ``` 60 | 61 | Create a schema using sync: 62 | 63 | ```js 64 | const loader = require('@creditkarma/graphql-loader') 65 | 66 | const schema = loader.loadSchema.sync('./schema/*.graphql') 67 | console.log(schema.getQueryType().toString()) 68 | 69 | ``` 70 | 71 | ## executableSchemaFromModules 72 | 73 | Given an array of GraphQL Modules or functions that returns a GraphQL Module or Promise, 74 | merge the documents and resolvers together and return an executable GraphQL Schema 75 | 76 | GraphQL modules are comprised of a document node and resolvers to provide away to decompose 77 | a GraphQL server into stand alone Node.js modules. These modules expose a DocumentNode because 78 | document nodes are valid GraphQL segments that are not required to be a complete valid schema. 79 | 80 | It is required that the combination of GraphQLModules results in a completely valid GraphQLSchema. 81 | 82 | ```js 83 | const modules = [ 84 | () => loadDocument('./fixtures/user/**/*.graphql').then((document) => ({ document, resolvers: {}})), 85 | () => loadDocument('./fixtures/swapi/**/*.graphql').then((document) => ({ document, resolvers: {}})), 86 | ] 87 | executableSchemaFromModules(modules).then((schema) => { 88 | console.log(schema.getQueryType().toString()) 89 | }) 90 | 91 | ``` 92 | 93 | ## loadDocument 94 | 95 | Given a GLOB pattern, load the matching files, combine them together and return a GraphQL AST in 96 | the form of a DocumentNode. The document node will be parsed and validate but doesn't have to meet all 97 | the requirements of a full schema definition. For example, it is possible to just load several files 98 | with only types defined. *NOTE:* You must use a DocumentNode with the combineDocuments function 99 | 100 | Load several GraphQL files into a single DocumentNode 101 | 102 | ```js 103 | const loader = require('@creditkarma/graphql-loader') 104 | 105 | loader.loadDocument('./schema/*.graphql').then((doc) => { 106 | console.log(doc) 107 | }) 108 | ``` 109 | ## combineDocuments 110 | 111 | Given an array of DocumentNodes, merge them together and return a GraphQLSchema 112 | * Any duplicate Type definitions will be merged by concatenating their fields 113 | * Any duplicate Schema definitions will be merged by concatenating their operations 114 | 115 | Combine several documents into a GraphqlSchema 116 | 117 | ```js 118 | const loader = require('@creditkarma/graphql-loader') 119 | 120 | Promise.all( 121 | loader.loadDocument('./ships/graphql/**/*.graphql'), 122 | loader.loadDocument('./planets/graphql/**/*.graphql') 123 | ).then((docs) => { 124 | const schema = combineDocuments(docs) 125 | console.log(schema.getQueryType().toString()) 126 | }) 127 | ``` 128 | 129 | ## Development 130 | 131 | Install dependencies with 132 | 133 | ```sh 134 | npm install 135 | ``` 136 | 137 | ### Build 138 | 139 | ```sh 140 | npm run build 141 | ``` 142 | 143 | 144 | ### Run test in watch mode 145 | 146 | ```sh 147 | npm run test:watch 148 | ``` 149 | 150 | ## Contributing 151 | For more information about contributing new features and bug fixes, see our [Contribution Guidelines](https://github.com/creditkarma/CONTRIBUTING.md). 152 | External contributors must sign Contributor License Agreement (CLA) 153 | 154 | ## License 155 | This project is licensed under [Apache License Version 2.0](./LICENSE) 156 | -------------------------------------------------------------------------------- /fixtures/swapi/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/swapi/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/swapi/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/swapi/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/swapi/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/swapi/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/swapi/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/swapi/schema.graphql: -------------------------------------------------------------------------------- 1 | schema { 2 | query: RootQuery 3 | } 4 | -------------------------------------------------------------------------------- /fixtures/user/schema.graphql: -------------------------------------------------------------------------------- 1 | type User { 2 | name: String! 3 | hash: String 4 | salt: String 5 | } 6 | type RootQuery { 7 | users: [User!] 8 | } 9 | schema { 10 | query: RootQuery 11 | } 12 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@creditkarma/graphql-loader", 3 | "version": "0.7.1", 4 | "description": "Build a GraphQL Schema by loading .graphql files based a glob pattern", 5 | "repository": { 6 | "url": "https://github.com/creditkarma/graphql-loader" 7 | }, 8 | "main": "./dist/index.js", 9 | "types": "./dist/index.d.ts", 10 | "scripts": { 11 | "clean": "rimraf coverage/ dist/ node_modules/ typings/", 12 | "build": "tsc", 13 | "build:watch": "tsc --watch", 14 | "lint": "tslint src/**/*", 15 | "pretest": "npm run build", 16 | "test": "npm run test:only --", 17 | "test:watch": "npm test -- -w", 18 | "test:only": "lab --coverage --sourcemaps ./dist/test", 19 | "coverage": "lab --coverage --sourcemaps -r console -o stdout -r html -o ./coverage/coverage.html ./dist/test", 20 | "prepublish": "npm test", 21 | "release:patch": "npm version patch && npm run release:publish", 22 | "release:minor": "npm version minor && npm run release:publish", 23 | "release:major": "npm version major && npm run release:publish", 24 | "release:publish": "npm publish && git push --follow-tags" 25 | }, 26 | "keywords": [ 27 | "GraphQL" 28 | ], 29 | "author": "Credit Karma", 30 | "license": "Apache-2.0", 31 | "devDependencies": { 32 | "@types/code": "^4.0.0", 33 | "@types/deepmerge": "^1.3.1", 34 | "@types/glob": "^5.0.30", 35 | "@types/graphql": "^0.11.0", 36 | "@types/mkdirp": "^0.5.2", 37 | "@types/node": "^6.0.46", 38 | "@types/rimraf": "2.0.2", 39 | "code": "^3.0.2", 40 | "lab": "^14.3.2", 41 | "mkdirp": "^0.5.1", 42 | "rimraf": "^2.6.2", 43 | "tslint": "^5.9.1", 44 | "typescript": "^2.6.2" 45 | }, 46 | "dependencies": { 47 | "deepmerge": "^2.0.1", 48 | "glob": "^7.1.2", 49 | "graphql": "^0.11.7", 50 | "graphql-tools": "^2.18.0" 51 | }, 52 | "peerDependencies": { 53 | "graphql": "^0.9.0 || ^0.10.1 || ^0.11.0" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import * as deepmerge from 'deepmerge' 2 | import * as fs from 'fs' 3 | import * as Glob from 'glob' 4 | import { 5 | buildASTSchema, 6 | DocumentNode, 7 | GraphQLSchema, 8 | ObjectTypeDefinitionNode, 9 | parse, 10 | SchemaDefinitionNode, 11 | } from 'graphql' 12 | import { addResolveFunctionsToSchema } from 'graphql-tools' 13 | 14 | import * as Kind from 'graphql/language/kinds' 15 | 16 | export class GraphQLLoaderError extends Error { 17 | public static zeroMatchError(glob: string): GraphQLLoaderError { 18 | return new GraphQLLoaderError(`The glob pattern "${glob}" has zero matches`) 19 | } 20 | constructor(message: string) { 21 | super(message) 22 | this.name = 'GraphQLLoaderError' 23 | } 24 | } 25 | 26 | export interface ISchemaCallback { 27 | (err: GraphQLLoaderError, schema: GraphQLSchema) 28 | } 29 | 30 | export interface ILoadSchemaFunc { 31 | (pattern: string, callback?: ISchemaCallback): Promise 32 | sync?: (pattern: string) => GraphQLSchema 33 | } 34 | 35 | export interface IGraphQLModule { 36 | document: DocumentNode, 37 | resolvers?: any 38 | } 39 | 40 | export type IGraphQLModuleFunction = () => IGraphQLModule | Promise 41 | 42 | /** 43 | * Given a GLOB pattern, it will load all the content of the files matching the GLOB, combine them 44 | * together and return a GraphQL Schema 45 | * @param pattern String - GLOB pattern 46 | * @param callback ISchemaCallback 47 | */ 48 | export const loadSchema: ILoadSchemaFunc = (pattern: string, callback?: ISchemaCallback): Promise => { 49 | return new Promise((resolve, reject) => { 50 | loadDocument(pattern) 51 | .then(buildASTSchema) 52 | .then((schema) => callback ? callback(null, schema) : resolve(schema)) 53 | .catch((err) => callback ? callback(err, null) : reject(err)) 54 | }) 55 | } 56 | 57 | /** 58 | * Given a GLOB pattern, load the matching files, combine them together and return a GraphQL AST in 59 | * the form of a DocumentNode 60 | * @param pattern String - GLOB pattern 61 | */ 62 | export const loadDocument = (pattern: string): Promise => 63 | getGlob(pattern).then(combineFiles).then(parse) 64 | 65 | /** 66 | * Given an array of DocumentNodes, merge them together and return a GraphQLSchema 67 | * * Any duplicate Type definitions will be merged by concating their fields 68 | * * Any duplicate Schema definitions will be merged by concating their operations 69 | * @param docs DocumentNode[] 70 | */ 71 | export const combineDocuments = (docs: DocumentNode[]): GraphQLSchema => 72 | buildASTSchema(concatAST(docs)) 73 | 74 | /** 75 | * Given an array of GraphQLModules or functions that return a GraphQLModule or Promise, 76 | * merge the documents and resolvers together and return an executable GraphQL Schema 77 | * @param modules IGraphQLModule[] | IGraphQLModuleFunction[] 78 | */ 79 | export const executableSchemaFromModules = 80 | (modules: IGraphQLModule[] | IGraphQLModuleFunction[]): Promise => { 81 | const promises = convertModulesToPromises(modules) 82 | return Promise.all(promises).then((gqlModules) => { 83 | const schema = combineDocuments(gqlModules.map((mod) => mod.document)) 84 | const resolvers = gqlModules.reduce((prev, curr) => deepmerge(prev, curr.resolvers || {}), {}) 85 | addResolveFunctionsToSchema(schema, resolvers) 86 | return schema 87 | }).catch((e) => { throw e }) 88 | } 89 | 90 | const convertModulesToPromises = 91 | (modules: IGraphQLModule[] | IGraphQLModuleFunction[]): Array> => { 92 | return (modules as IGraphQLModuleFunction[]).map((mod) => { 93 | const result = typeof mod === 'function' ? mod() : mod 94 | if ((result as IGraphQLModule).document) { 95 | return Promise.resolve(result) 96 | } else { 97 | return result as Promise 98 | } 99 | }) 100 | } 101 | 102 | const filterDups = (dups: ObjectTypeDefinitionNode[], doc: ObjectTypeDefinitionNode, index: number, orig) => { 103 | const hasDups = orig.filter((_) => _.name.value === doc.name.value).length > 1 104 | const docInDups = dups.find((_) => _.name.value === doc.name.value) 105 | return hasDups && !docInDups ? dups.concat(doc) : dups 106 | } 107 | 108 | const mergeFields = (allDefs: ObjectTypeDefinitionNode[]) => (dup) => { 109 | allDefs.forEach((def) => { 110 | if (def.name && def.name.value === dup.name.value && def !== dup) { 111 | dup.fields = dup.fields.concat(def.fields) 112 | } 113 | }) 114 | return dup 115 | } 116 | 117 | const mergeOperations = (allDefs: SchemaDefinitionNode[]) => (dup) => { 118 | allDefs.forEach((def) => { 119 | if (def.kind === Kind.SCHEMA_DEFINITION && def !== dup) { 120 | const findTypes = (opType) => !dup.operationTypes.find((dupType) => dupType.operation === opType.operation) 121 | const deduped = def.operationTypes.filter(findTypes) 122 | dup.operationTypes = dup.operationTypes.concat(deduped) 123 | } 124 | }) 125 | return dup 126 | } 127 | 128 | const isKind = (kind) => (def) => def.kind === kind 129 | 130 | const filterSchemaAndDups = (dups) => (def) => { 131 | return def.kind !== Kind.SCHEMA_DEFINITION && !dups.find((_) => _.name.value === def.name.value) 132 | } 133 | 134 | const concatAST = (documents: DocumentNode[]): DocumentNode => { 135 | const allDefs = documents.reduce((defs, doc) => defs.concat(doc.definitions), []) 136 | 137 | // find all duplicate type definitions and merge their fields together 138 | const dups = allDefs.filter(isKind(Kind.OBJECT_TYPE_DEFINITION)).reduce(filterDups, []).map(mergeFields(allDefs)) 139 | // find all duplicate schema definitions and merge their operations together 140 | const schemas = allDefs.filter(isKind(Kind.SCHEMA_DEFINITION)).slice(0, 1).map(mergeOperations(allDefs)) 141 | 142 | const definitions = allDefs.filter(filterSchemaAndDups(dups)).concat(schemas, dups) 143 | 144 | return { 145 | definitions, 146 | kind: 'Document', 147 | } 148 | } 149 | 150 | const combineFiles = (fileNames: string[]): Promise => { 151 | const promises = fileNames.map(readFile) 152 | return Promise.all( promises ) 153 | .then((fileContents) => fileContents.join()) 154 | .catch((err) => { throw err }) 155 | } 156 | 157 | const getGlob = (pattern: string): Promise => { 158 | return new Promise((resolve, reject) => { 159 | Glob(pattern, (err, files) => { 160 | if (files.length === 0) { 161 | reject(GraphQLLoaderError.zeroMatchError(pattern) ) 162 | } else { 163 | resolve(files) 164 | } 165 | }) 166 | }) 167 | } 168 | 169 | const readFile = (fileName: string): Promise => { 170 | return new Promise((resolve, reject) => { 171 | fs.readFile(fileName, 'utf8', (err, data) => { 172 | if (err) { 173 | reject(err) 174 | } else { 175 | resolve(data) 176 | } 177 | }) 178 | }) 179 | } 180 | 181 | loadSchema.sync = (pattern: string): GraphQLSchema => { 182 | const fileNames = getGlobSync(pattern) 183 | const schema = makeSchemaSync(fileNames) 184 | return buildASTSchema(parse(schema)) 185 | } 186 | 187 | const getGlobSync = (pattern: string) => { 188 | const fileNames = Glob.sync(pattern) 189 | if (fileNames.length === 0) { 190 | throw GraphQLLoaderError.zeroMatchError(pattern) 191 | } else { 192 | return fileNames 193 | } 194 | } 195 | 196 | const makeSchemaSync = (fileNames: string[]) => { 197 | return fileNames.map(readFileSync).join() 198 | } 199 | 200 | const readFileSync = (fileName: string): string => { 201 | return fs.readFileSync(fileName, 'utf8') 202 | } 203 | -------------------------------------------------------------------------------- /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 * as fs from 'fs' 10 | import { DocumentNode, GraphQLSchema } from 'graphql' 11 | import * as mkdirp from 'mkdirp' 12 | import * as rimraf from 'rimraf' 13 | import { 14 | combineDocuments, 15 | executableSchemaFromModules, 16 | GraphQLLoaderError, 17 | loadDocument, 18 | loadSchema, 19 | } from '../index' 20 | 21 | const glob = './fixtures/swapi/**/*.graphql' 22 | const userGlob = './fixtures/user/**/*.graphql' 23 | const invalidGlob = './error/*.graphql' 24 | const invalidSchemaGlob = './fixtures/swapi/*.graphql' 25 | 26 | const invalidGlobPattern = /has zero matches/ 27 | const invalidSchemaPattern = /Type .* not found in document./ 28 | 29 | describe('Sync Schema Loader', () => { 30 | describe(`when glob loading with complete schema "${glob}"`, () => { 31 | const schema = loadSchema.sync(glob) 32 | 33 | it('expect schema to be a graphql schema', (done) => { 34 | expect(schema).to.exist() 35 | expect(schema).to.be.an.instanceof(GraphQLSchema) 36 | done() 37 | }) 38 | }) 39 | 40 | describe(`when loading an invalid glob "${invalidGlob}"`, () => { 41 | it('expect error to be triggered', (done) => { 42 | const throws = () => { loadSchema.sync(invalidGlob) } 43 | expect( throws ).to.throw(GraphQLLoaderError, invalidGlobPattern) 44 | done() 45 | }) 46 | }) 47 | describe(`when loading glob with invalid schema ${invalidSchemaGlob}`, () => { 48 | it('expect schema errors to exist', (done) => { 49 | const throws = () => { loadSchema.sync(invalidSchemaGlob) } 50 | expect( throws ).to.throw(Error, invalidSchemaPattern) 51 | done() 52 | }) 53 | }) 54 | }) 55 | 56 | describe('Schema Loader', () => { 57 | describe(`when loading glob with complete schema "${glob}"`, () => { 58 | let schema 59 | let cbSchema 60 | before((done) => { 61 | loadSchema(glob).then((results) => { 62 | schema = results 63 | loadSchema(glob, (err, cbResults) => { 64 | cbSchema = cbResults 65 | done() 66 | }) 67 | }) 68 | }) 69 | 70 | it('expect schema to be a graphql schema', (done) => { 71 | expect(schema).to.exist() 72 | expect(schema).to.be.an.instanceof(GraphQLSchema) 73 | done() 74 | }) 75 | 76 | it('expect callback schema to be a graphql schema', (done) => { 77 | expect(cbSchema).to.exist() 78 | expect(cbSchema).to.be.an.instanceof(GraphQLSchema) 79 | done() 80 | }) 81 | }) 82 | 83 | describe(`when loading an invalid glob "${invalidGlob}"`, () => { 84 | let schemaErrors 85 | let cbSchemaErrors 86 | before((done) => { 87 | loadSchema(invalidGlob).catch((err) => { 88 | schemaErrors = err 89 | loadSchema(invalidGlob, (cbErr) => { 90 | cbSchemaErrors = cbErr 91 | done() 92 | }) 93 | }) 94 | }) 95 | 96 | it('expect glob error to be triggered', (done) => { 97 | expect(schemaErrors).to.exist() 98 | expect(schemaErrors.message).to.match(invalidGlobPattern) 99 | done() 100 | }) 101 | 102 | it('expect callbaack glob error to be triggered', (done) => { 103 | expect(cbSchemaErrors).to.exist() 104 | expect(cbSchemaErrors.message).to.match(invalidGlobPattern) 105 | done() 106 | }) 107 | }) 108 | 109 | describe(`when loading glob with invalid schema "${invalidSchemaGlob}"`, () => { 110 | let schemaErrors 111 | let cbSchemaErrors 112 | before((done) => { 113 | loadSchema(invalidSchemaGlob).catch((err) => { 114 | schemaErrors = err 115 | loadSchema(invalidSchemaGlob, (cbErr) => { 116 | cbSchemaErrors = cbErr 117 | done() 118 | }) 119 | }) 120 | }) 121 | 122 | it('expect error to be invalidSchemaPattern', (done) => { 123 | expect(schemaErrors).to.exist() 124 | expect(schemaErrors).to.match(invalidSchemaPattern) 125 | done() 126 | }) 127 | it('expect callback error to be invalidSchemaPattern', (done) => { 128 | expect(schemaErrors).to.exist() 129 | expect(schemaErrors).to.match(invalidSchemaPattern) 130 | done() 131 | }) 132 | }) 133 | 134 | describe('when loading glob with unreadable files', () => { 135 | const root = './fixtures/unreadable' 136 | const badGlob = `${root}/*.graphql` 137 | let results 138 | let cbResults 139 | before((done) => { 140 | mkdirp(root, () => { 141 | fs.writeFile(`${root}/schema.graphql`, 'hello', {mode: '333'}, (err) => { 142 | loadSchema(badGlob).catch((r) => { 143 | results = r 144 | loadSchema(badGlob, (cbr) => { 145 | cbResults = cbr 146 | rimraf(root, done) 147 | }) 148 | }) 149 | }) 150 | }) 151 | }) 152 | 153 | it('expect error to exist', (done) => { 154 | expect(results).to.exist() 155 | done() 156 | }) 157 | it('expect callback error to exist', (done) => { 158 | expect(cbResults).to.exist() 159 | done() 160 | }) 161 | }) 162 | }) 163 | 164 | describe('Loading Document', () => { 165 | describe(`when loading glob with complete schema "${glob}"`, () => { 166 | let doc: DocumentNode 167 | before(() => loadDocument(glob).then((results) => doc = results)) 168 | 169 | it('expect schema to be a graphql schema', (done) => { 170 | expect(doc).to.exist() 171 | expect(doc.kind).to.equal('Document') 172 | done() 173 | }) 174 | }) 175 | }) 176 | 177 | describe('Combing Documents', () => { 178 | describe(`when loading glob with complete schema "${userGlob}"`, () => { 179 | let doc: DocumentNode 180 | let schema: GraphQLSchema 181 | before(() => { 182 | return Promise.all([ 183 | loadDocument(userGlob), 184 | loadDocument(glob), 185 | ]).then((results) => { 186 | doc = results[0] 187 | schema = combineDocuments(results) 188 | }) 189 | }) 190 | 191 | it('expect schema to be a graphql schema', (done) => { 192 | expect(schema).to.exist() 193 | expect(schema).to.be.an.instanceof(GraphQLSchema) 194 | done() 195 | }) 196 | }) 197 | }) 198 | 199 | describe('Build Executable Schema From GraphQL Modules', () => { 200 | describe(`when preloading documents`, () => { 201 | let schema: GraphQLSchema 202 | before(() => { 203 | return Promise.all([ 204 | loadDocument(userGlob), 205 | loadDocument(glob), 206 | ]).then((results) => { 207 | const modules = results.map((document) => ({ document, resolvers: {} })) 208 | return executableSchemaFromModules(modules).then((execSchema) => schema = execSchema) 209 | }) 210 | }) 211 | 212 | it('expect schema to be a graphql schema', (done) => { 213 | expect(schema).to.exist() 214 | expect(schema).to.be.an.instanceof(GraphQLSchema) 215 | done() 216 | }) 217 | }) 218 | 219 | describe(`when providing array of functions`, () => { 220 | let schema: GraphQLSchema 221 | before(() => { 222 | return Promise.all([ 223 | loadDocument(userGlob), 224 | loadDocument(glob), 225 | ]).then((results) => { 226 | const modules = results.map((document) => () => ({ document, resolvers: {} })) 227 | return executableSchemaFromModules(modules).then((execSchema) => schema = execSchema) 228 | }) 229 | }) 230 | 231 | it('expect schema to be a graphql schema', (done) => { 232 | expect(schema).to.exist() 233 | expect(schema).to.be.an.instanceof(GraphQLSchema) 234 | done() 235 | }) 236 | }) 237 | 238 | describe(`when using promises`, () => { 239 | let schema: GraphQLSchema 240 | before(() => { 241 | const modules = [ 242 | () => loadDocument(userGlob).then((document) => ({ document, resolvers: {}})), 243 | () => loadDocument(glob).then((document) => ({ document })), 244 | ] 245 | return executableSchemaFromModules(modules).then((execSchema) => schema = execSchema) 246 | }) 247 | 248 | it('expect schema to be a graphql schema', (done) => { 249 | expect(schema).to.exist() 250 | expect(schema).to.be.an.instanceof(GraphQLSchema) 251 | done() 252 | }) 253 | }) 254 | }) 255 | -------------------------------------------------------------------------------- /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 | "lib": [ 19 | "esnext" 20 | ] 21 | }, 22 | "exclude": [ 23 | "node_modules", 24 | "dist" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------