├── .babelrc ├── .eslintignore ├── .eslintrc.js ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── package.json └── src ├── build ├── __tests__ │ ├── build-test.js │ ├── buildEnum-test.js │ ├── buildFieldConfigMap-test.js │ ├── buildInputObject-test.js │ ├── buildInterface-test.js │ ├── buildObject-test.js │ ├── buildScalar-test.js │ ├── buildSchema-test.js │ ├── buildUnion-test.js │ ├── comparators.js │ ├── produceType-test.js │ ├── resolveShortcut-test.js │ └── resolveThunk-test.js ├── buildEnum.js ├── buildFieldConfigMap.js ├── buildInputObject.js ├── buildInterface.js ├── buildObject.js ├── buildScalar.js ├── buildSchema.js ├── buildUnion.js ├── index.js ├── produceType.js ├── resolveShortcut.js └── resolveThunk.js └── index.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "latest", 4 | "stage-0" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | !.eslintrc.js 2 | lib 3 | coverage 4 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: 'airbnb-base', 3 | parser: 'babel-eslint', 4 | plugins: [ 5 | 'babel', 6 | ], 7 | rules: { 8 | 'babel/func-params-comma-dangle': ['error', 'always-multiline'], 9 | }, 10 | }; 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | npm-debug.log 4 | lib 5 | coverage 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "4" 4 | - "5" 5 | - "6" 6 | script: 7 | - npm test -- --coverage && cat coverage/lcov.info | node_modules/coveralls/bin/coveralls.js 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016-present Bloveit, Inc. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # graphql-utilities 2 | [![npm version](https://badge.fury.io/js/graphql-utilities.svg)](https://badge.fury.io/js/graphql-utilities) [![Build Status](https://travis-ci.org/bloveit/graphql-utilities.svg?branch=master)](https://travis-ci.org/bloveit/graphql-utilities) [![Coverage Status](https://coveralls.io/repos/github/bloveit/graphql-utilities/badge.svg?branch=master)](https://coveralls.io/github/bloveit/graphql-utilities?branch=master) 3 | 4 | Inspired by [`graph.ql`](https://github.com/MatthewMueller/graph.ql), [`graphql-tools`](https://github.com/apollostack/graphql-tools), and [`graphql-helpers`](https://github.com/depop/graphql-helpers). 5 | 6 | ## Why? 7 | There are various libraries out there providing utilities for GraphQL and even the [reference implementation](https://github.com/graphql/graphql-js) itself is adding [new utilities](https://github.com/graphql/graphql-js/pull/471). So why do we need another one? 8 | 9 | None of those libraries let you build GraphQL types using the schema language. This prevents gradual adoption of the tools and makes code separation and isolation a nightmare. 10 | 11 | With `graphql-utilities` it's simple. `build` makes it extremely simple to build a GraphQL type. 12 | 13 | ```js 14 | build(` 15 | type Query { 16 | ok: Boolean! 17 | } 18 | `); 19 | 20 | /* is equivalent to */ 21 | 22 | new GraphQLObjectType({ 23 | name: 'Query', 24 | fields: () => ({ 25 | ok: { type: new GraphQLNonNull(GraphQLBoolean) }, 26 | }), 27 | }) 28 | ``` 29 | 30 | ## Installation 31 | ``` 32 | npm install --save graphql-utilities 33 | ``` 34 | 35 | ## Getting Started 36 | ```js 37 | import { build } from 'graphql-utilities'; 38 | 39 | // you can build a type 40 | const Record = build(` 41 | interface Record { 42 | id: ID! 43 | } 44 | `); 45 | 46 | // or you can build a schema 47 | const Schema = build(` 48 | schema { 49 | query: Query 50 | } 51 | 52 | type Query { 53 | ok: Boolean! 54 | } 55 | `); 56 | ``` 57 | 58 | ## TODO 59 | - [ ] Add detailed API docs. 60 | - [x] ~~Make `build` configuration interchangeable with types.~~ 61 | - [x] ~~Allow `build` to accept a flag to skip inferred schema.~~ 62 | 63 | ## License 64 | MIT 65 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "graphql-utilities", 3 | "version": "0.0.14", 4 | "description": "Utilities for GraphQL", 5 | "author": "Miguel Oller ", 6 | "license": "MIT", 7 | "repository": { 8 | "type": "git", 9 | "url": "https://github.com/bloveit/graphql-utilities.git" 10 | }, 11 | "bugs": "https://github.com/bloveit/graphql-utilities/issues", 12 | "keywords": [ 13 | "GraphQL" 14 | ], 15 | "main": "lib", 16 | "files": [ 17 | "lib" 18 | ], 19 | "scripts": { 20 | "lint": "eslint .", 21 | "test": "jest", 22 | "build": "babel src -d lib --ignore __tests__", 23 | "prepublish": "npm run lint && npm run test && npm run build" 24 | }, 25 | "peerDependencies": { 26 | "graphql": ">=0.7.0" 27 | }, 28 | "devDependencies": { 29 | "babel-cli": "^6.14.0", 30 | "babel-eslint": "^6.1.2", 31 | "babel-jest": "^15.0.0", 32 | "babel-polyfill": "^6.13.0", 33 | "babel-preset-es2015": "^6.14.0", 34 | "babel-preset-es2017": "^6.14.0", 35 | "babel-preset-latest": "^6.14.0", 36 | "babel-preset-stage-0": "^6.5.0", 37 | "coveralls": "^2.11.12", 38 | "eslint": "^3.4.0", 39 | "eslint-config-airbnb-base": "^5.0.3", 40 | "eslint-plugin-babel": "^3.3.0", 41 | "eslint-plugin-import": "^1.14.0", 42 | "graphql": "^0.7.0", 43 | "jest": "^15.1.1" 44 | }, 45 | "jest": { 46 | "collectCoverageFrom": [ 47 | "src/**/*.js", 48 | "!src/index.js", 49 | "!src/**/__tests__/**" 50 | ], 51 | "testEnvironment": "node", 52 | "testRegex": "__tests__/.*-test.js$" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/build/__tests__/build-test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | import { 4 | GraphQLSchema, 5 | GraphQLScalarType, 6 | GraphQLObjectType, 7 | GraphQLInterfaceType, 8 | GraphQLNonNull, 9 | GraphQLBoolean, 10 | GraphQLID, 11 | DirectiveLocation, 12 | GraphQLDirective, 13 | } from 'graphql/type'; 14 | import { parse } from 'graphql/language'; 15 | import { expectTypesEqual, expectSchemasEqual } from './comparators'; 16 | import build, { buildTypes, SCHEMA_CONFIG_KEY } from '../'; 17 | 18 | const CustomDirective = new GraphQLDirective({ 19 | name: 'CustomDirective', 20 | locations: [DirectiveLocation.FIELD], 21 | }); 22 | const querySource = ` 23 | type Query { 24 | ok: Boolean! 25 | } 26 | `; 27 | const queryWithDirectiveSource = ` 28 | type Query { 29 | ok: Boolean! @CustomDirective 30 | } 31 | `; 32 | const generateQuery = (resolve) => new GraphQLObjectType({ 33 | name: 'Query', 34 | fields: { ok: { type: new GraphQLNonNull(GraphQLBoolean), resolve } }, 35 | }); 36 | const schemaSource = ` 37 | schema { 38 | query: Query 39 | } 40 | `; 41 | const Schema = new GraphQLSchema({ query: generateQuery() }); 42 | const SchemaWithDirective = new GraphQLSchema({ 43 | directives: [CustomDirective], 44 | query: generateQuery(), 45 | }); 46 | const timestampSource = ` 47 | scalar Timestamp 48 | `; 49 | const serialize = (date) => Date.prototype.toISOString.call(date); 50 | const Timestamp = new GraphQLScalarType({ name: 'Timestamp', serialize }); 51 | const recordSource = ` 52 | interface Record { 53 | id: ID! 54 | createdAt: Timestamp! 55 | updatedAt: Timestamp! 56 | } 57 | `; 58 | const Record = new GraphQLInterfaceType({ 59 | name: 'Record', 60 | fields: { 61 | id: { type: new GraphQLNonNull(GraphQLID) }, 62 | createdAt: { type: new GraphQLNonNull(Timestamp) }, 63 | updatedAt: { type: new GraphQLNonNull(Timestamp) }, 64 | }, 65 | }); 66 | 67 | describe('buildTypes()', () => { 68 | it('should work without types in AST', () => { 69 | expect(buildTypes(parse(schemaSource))).toEqual([]); 70 | }); 71 | 72 | it('should work with types in AST', () => { 73 | buildTypes(parse(querySource)) 74 | .forEach((type, i) => expectTypesEqual(type, [generateQuery()][i])); 75 | }); 76 | 77 | it('should work with config map', () => { 78 | const ok = () => true; 79 | buildTypes(parse(querySource), { Query: { ok } }) 80 | .forEach((type, i) => expectTypesEqual(type, [generateQuery(ok)][i])); 81 | }); 82 | 83 | it('should work with type dependencies', () => { 84 | buildTypes(parse(recordSource), undefined, [Timestamp]) 85 | .forEach((type, i) => expectTypesEqual(type, [Record, Timestamp][i])); 86 | }); 87 | 88 | it('should throw with duplicate types in type dependencies', () => { 89 | const msg = `Duplicate type "${Record.name}" in schema definition or type dependencies.`; 90 | expect(() => { 91 | const types = buildTypes(parse(recordSource), undefined, [Record]); 92 | types[0].getFields(); 93 | }).toThrowError(msg); 94 | expect(() => { 95 | const types = buildTypes(parse(querySource + recordSource), undefined, [Record]); 96 | types[1].getFields(); 97 | }).toThrowError(msg); 98 | }); 99 | }); 100 | 101 | describe('build()', () => { 102 | it('should throw if source is not a string', () => { 103 | expect(() => build()).toThrowError('Expected a string but got undefined.'); 104 | }); 105 | 106 | it('should throw if config is not an object', () => { 107 | expect(() => build(querySource, null)).toThrowError('Expected an object but got null.'); 108 | }); 109 | 110 | it('should throw if types is not an array or a function', () => { 111 | expect(() => build(querySource, undefined, null)) 112 | .toThrowError('Expected an array or a function but got null.'); 113 | }); 114 | 115 | it('should throw if inference flag is not a boolean', () => { 116 | expect(() => build(querySource, undefined, undefined, null)) 117 | .toThrowError('Expected a boolean but got null.'); 118 | }); 119 | 120 | it('should allow config, types, and inference flag to be optional', () => { 121 | expectTypesEqual(build(querySource, {}, false), generateQuery()); 122 | expectTypesEqual(build(querySource, [], false), generateQuery()); 123 | expectSchemasEqual(build(querySource, []), Schema); 124 | expectTypesEqual(build(querySource, false), generateQuery()); 125 | }); 126 | 127 | it('should throw with duplicate types in AST', () => { 128 | expect(() => build(recordSource + recordSource)) 129 | .toThrowError(`Duplicate type "${Record.name}" in schema definition or type dependencies.`); 130 | }); 131 | 132 | it('should throw with duplicate schema declarations', () => { 133 | expect(() => build(schemaSource + schemaSource)) 134 | .toThrowError('Must provide only one schema definition.'); 135 | }); 136 | 137 | it('should work with one type in source', () => { 138 | expectTypesEqual(build(recordSource, undefined, [Timestamp]), Record); 139 | }); 140 | 141 | it('should throw if building a schema and types is not an array', () => { 142 | const msg = 'Can\'t use thunks as type dependencies for schema.'; 143 | expect(() => build(schemaSource + querySource, undefined, () => {})).toThrowError(msg); 144 | expect(() => build(querySource, undefined, () => {})).toThrowError(msg); 145 | }); 146 | 147 | it('should work with schema in source', () => { 148 | expectSchemasEqual(build(schemaSource + querySource), Schema); 149 | }); 150 | 151 | it('should work with inferred schema', () => { 152 | expectSchemasEqual(build(querySource), Schema); 153 | }); 154 | 155 | it('should allow to skip schema inference', () => { 156 | expectTypesEqual(build(querySource, undefined, undefined, false), generateQuery()); 157 | }); 158 | 159 | it('should work with multiple types in source', () => { 160 | Object.values(build(recordSource + timestampSource, { 161 | Timestamp: { serialize }, 162 | })).forEach((type, i) => expectTypesEqual(type, [Record, Timestamp][i])); 163 | Object.values(build(recordSource + timestampSource, { 164 | Timestamp: { serialize }, 165 | }, undefined, false)).forEach((type, i) => expectTypesEqual(type, [Record, Timestamp][i])); 166 | }); 167 | 168 | it('should allow schema configuration using SCHEMA_CONFIG_KEY', () => { 169 | const config = {}; 170 | config[SCHEMA_CONFIG_KEY] = { directives: [CustomDirective] }; 171 | const target = build(schemaSource + queryWithDirectiveSource, config); 172 | expectSchemasEqual(target, SchemaWithDirective); 173 | }); 174 | }); 175 | -------------------------------------------------------------------------------- /src/build/__tests__/buildEnum-test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | import { GraphQLEnumType } from 'graphql/type'; 4 | import { parse } from 'graphql/language'; 5 | import buildEnum, { buildEnumValueConfigMap } from '../buildEnum'; 6 | 7 | const generateEnumAST = ({ description, name = 'Enum', values = ['VALUE'] } = {}) => parse(` 8 | # ${description === undefined ? '' : description} 9 | enum ${name} { 10 | ${values.join('\n')} 11 | } 12 | `).definitions[0]; 13 | const generateEnumValueConfigMap = ({ 14 | name = 'VALUE', 15 | value = 'VALUE', 16 | description, 17 | deprecationReason, 18 | } = {}) => ({ [name]: { value, description, deprecationReason } }); 19 | 20 | describe('buildEnumValueConfigMap()', () => { 21 | it('should work with minimal AST', () => { 22 | expect(buildEnumValueConfigMap(generateEnumAST())).toEqual(generateEnumValueConfigMap()); 23 | }); 24 | 25 | it('should work with description in AST', () => { 26 | const description = 'Another description.'; 27 | expect(buildEnumValueConfigMap(generateEnumAST({ 28 | values: [`# ${description}\nVALUE`], 29 | }))).toEqual(generateEnumValueConfigMap({ description })); 30 | }); 31 | 32 | it('should work with `value` in config map', () => { 33 | const value = 'value'; 34 | expect(buildEnumValueConfigMap(generateEnumAST(), { VALUE: { value } })) 35 | .toEqual(generateEnumValueConfigMap({ value })); 36 | }); 37 | 38 | it('should work with `deprecationReason` in config map', () => { 39 | const deprecationReason = 'A reason.'; 40 | expect(buildEnumValueConfigMap(generateEnumAST(), { VALUE: { deprecationReason } })) 41 | .toEqual(generateEnumValueConfigMap({ deprecationReason })); 42 | }); 43 | }); 44 | 45 | describe('buildEnum()', () => { 46 | const generateEnumType = ({ 47 | name = 'Enum', 48 | values = generateEnumValueConfigMap(), 49 | description, 50 | } = {}) => new GraphQLEnumType({ name, values, description }); 51 | 52 | it('should work with minimal AST', () => { 53 | expect(buildEnum(generateEnumAST())).toEqual(generateEnumType()); 54 | }); 55 | 56 | it('should work with description in AST', () => { 57 | const config = { description: 'A description.' }; 58 | expect(buildEnum(generateEnumAST(config))).toEqual(generateEnumType(config)); 59 | }); 60 | 61 | it('should work with `values` in config', () => { 62 | const config = { values: { VALUE: { value: 'value' } } }; 63 | expect(buildEnum(generateEnumAST(), config)).toEqual(generateEnumType(config)); 64 | }); 65 | }); 66 | -------------------------------------------------------------------------------- /src/build/__tests__/buildFieldConfigMap-test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | import { GraphQLInt } from 'graphql/type'; 4 | import { parse } from 'graphql/language'; 5 | import buildFieldConfigMap, { buildFieldConfigArgumentMap } from '../buildFieldConfigMap'; 6 | 7 | const generateTypeAST = ({ 8 | name = 'Object', 9 | fields = { field: 'Int' }, 10 | } = {}) => parse(` 11 | type ${name} { 12 | ${Object.entries(fields).map((entry) => entry.join(': ')).join('\n')} 13 | } 14 | `).definitions[0]; 15 | 16 | describe('buildFieldConfigArgumentMap()', () => { 17 | const generateArgumentFieldAST = ({ 18 | name = 'field', 19 | args = { argument: 'Int' }, 20 | } = {}) => generateTypeAST({ 21 | fields: { 22 | [` 23 | ${name}( 24 | ${Object.entries(args).map((entry) => entry.join(': ')).join('\n')} 25 | ) 26 | `]: 'Int', 27 | }, 28 | }).fields[0]; 29 | const generateFieldConfigMap = ({ 30 | name = 'argument', 31 | type = GraphQLInt, 32 | defaultValue, 33 | description, 34 | } = {}) => ({ [name]: { type, defaultValue, description } }); 35 | 36 | it('should work with minimal AST', () => { 37 | expect(buildFieldConfigArgumentMap(generateArgumentFieldAST())) 38 | .toEqual(generateFieldConfigMap()); 39 | }); 40 | 41 | it('should work with description in AST', () => { 42 | const description = 'A description.'; 43 | expect(buildFieldConfigArgumentMap(generateArgumentFieldAST({ 44 | args: { [`# ${description}\nargument`]: 'Int' }, 45 | }))).toEqual(generateFieldConfigMap({ description })); 46 | }); 47 | 48 | it('should work with default value in AST', () => { 49 | expect(buildFieldConfigArgumentMap(generateArgumentFieldAST({ 50 | args: { argument: 'Int = 0' }, 51 | }))).toEqual(generateFieldConfigMap({ defaultValue: 0 })); 52 | }); 53 | }); 54 | 55 | describe('buildFieldConfigMap()', () => { 56 | const generateFieldConfigMap = ({ 57 | name = 'field', 58 | type = GraphQLInt, 59 | args, 60 | resolve, 61 | deprecationReason, 62 | description, 63 | } = {}) => ({ [name]: { type, args, resolve, deprecationReason, description } }); 64 | it('should work with minimal AST', () => { 65 | expect(buildFieldConfigMap(generateTypeAST())).toEqual(generateFieldConfigMap()); 66 | }); 67 | 68 | it('should work with description in AST', () => { 69 | const description = 'A description.'; 70 | expect(buildFieldConfigMap(generateTypeAST({ 71 | fields: { [`# ${description}\nfield`]: 'Int' }, 72 | }))).toEqual(generateFieldConfigMap({ description })); 73 | }); 74 | 75 | it('should work with arguments in AST', () => { 76 | expect(buildFieldConfigMap(generateTypeAST({ 77 | fields: { 'field(argument: Int)': 'Int' }, 78 | }))).toEqual(generateFieldConfigMap({ args: { argument: { type: GraphQLInt } } })); 79 | }); 80 | 81 | it('should work with arguments in AST and `args` in config map', () => { 82 | const args = { argument: { type: GraphQLInt } }; 83 | expect(buildFieldConfigMap(generateTypeAST({ 84 | fields: { 'field(argument: Int)': 'Int' }, 85 | }), { field: args })).toEqual(generateFieldConfigMap({ args })); 86 | }); 87 | 88 | it('should work with `resolve` in config map', () => { 89 | const resolve = () => {}; 90 | expect(buildFieldConfigMap(generateTypeAST(), { field: { resolve } })) 91 | .toEqual(generateFieldConfigMap({ resolve })); 92 | }); 93 | 94 | it('should work with `deprecationReason` in config map', () => { 95 | const deprecationReason = 'A reason.'; 96 | expect(buildFieldConfigMap(generateTypeAST(), { field: { deprecationReason } })) 97 | .toEqual(generateFieldConfigMap({ deprecationReason })); 98 | }); 99 | }); 100 | -------------------------------------------------------------------------------- /src/build/__tests__/buildInputObject-test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | import { GraphQLInputObjectType, GraphQLInt } from 'graphql/type'; 4 | import { parse } from 'graphql/language'; 5 | import { expectTypesEqual } from './comparators'; 6 | import buildInputObject, { buildInputObjectConfigFieldMap } from '../buildInputObject'; 7 | 8 | const generateInputObjectAST = ({ 9 | description, 10 | name = 'Object', 11 | fields = { field: 'Int' }, 12 | } = {}) => parse(` 13 | # ${description === undefined ? '' : description} 14 | input ${name} { 15 | ${Object.entries(fields).map((entry) => entry.join(': ')).join('\n')} 16 | } 17 | `).definitions[0]; 18 | 19 | describe('buildInputObjectConfigFieldMap()', () => { 20 | const generateInputObjectConfigFieldMap = ({ 21 | name = 'field', 22 | type = GraphQLInt, 23 | defaultValue, 24 | description, 25 | } = {}) => ({ [name]: { type, defaultValue, description } }); 26 | 27 | it('should work with minimal AST', () => { 28 | expect(buildInputObjectConfigFieldMap(generateInputObjectAST())) 29 | .toEqual(generateInputObjectConfigFieldMap()); 30 | }); 31 | 32 | it('should work with description in AST', () => { 33 | const description = 'A description.'; 34 | expect(buildInputObjectConfigFieldMap(generateInputObjectAST({ 35 | fields: { [`# ${description}\nfield`]: 'Int' }, 36 | }))).toEqual(generateInputObjectConfigFieldMap({ description })); 37 | }); 38 | 39 | it('should work with default value in AST', () => { 40 | expect(buildInputObjectConfigFieldMap(generateInputObjectAST({ 41 | fields: { field: 'Int = 0' }, 42 | }))).toEqual(generateInputObjectConfigFieldMap({ defaultValue: 0 })); 43 | }); 44 | }); 45 | 46 | describe('buildInputObject()', () => { 47 | const generateInputObjectType = ({ 48 | name = 'Object', 49 | fields = { field: { type: GraphQLInt } }, 50 | description, 51 | } = {}) => new GraphQLInputObjectType({ name, fields, description }); 52 | 53 | it('should work with minimal AST', () => { 54 | expectTypesEqual(buildInputObject(generateInputObjectAST()), generateInputObjectType()); 55 | }); 56 | 57 | it('should work with description in AST', () => { 58 | const config = { description: 'A description.' }; 59 | expectTypesEqual( 60 | buildInputObject(generateInputObjectAST(config)), 61 | generateInputObjectType(config), 62 | ); 63 | }); 64 | }); 65 | -------------------------------------------------------------------------------- /src/build/__tests__/buildInterface-test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | import { GraphQLInterfaceType, GraphQLInt } from 'graphql/type'; 4 | import { parse } from 'graphql/language'; 5 | import { expectTypesEqual } from './comparators'; 6 | import buildInterface from '../buildInterface'; 7 | 8 | describe('buildInterface()', () => { 9 | const generateInterfaceAST = ({ 10 | description, 11 | name = 'Interface', 12 | fields = { field: 'Int' }, 13 | } = {}) => parse(` 14 | # ${description === undefined ? '' : description} 15 | interface ${name} { 16 | ${Object.entries(fields).map((entry) => entry.join(': ')).join('\n')} 17 | } 18 | `).definitions[0]; 19 | const generateInterfaceType = ({ 20 | name = 'Interface', 21 | fields = { field: { type: GraphQLInt } }, 22 | resolveType, 23 | description, 24 | } = {}) => new GraphQLInterfaceType({ name, fields, resolveType, description }); 25 | 26 | it('should work with minimal AST', () => { 27 | expectTypesEqual(buildInterface(generateInterfaceAST()), generateInterfaceType()); 28 | }); 29 | 30 | it('should work with description in AST', () => { 31 | const config = { description: 'A description.' }; 32 | expectTypesEqual(buildInterface(generateInterfaceAST(config)), generateInterfaceType(config)); 33 | }); 34 | 35 | it('should work with `resolve` shortcut', () => { 36 | const resolve = () => {}; 37 | expectTypesEqual( 38 | buildInterface(generateInterfaceAST(), { field: resolve }), 39 | generateInterfaceType({ fields: { field: { type: GraphQLInt, resolve } } }), 40 | ); 41 | }); 42 | 43 | it('should work with `fields` in config', () => { 44 | const deprecationReason = 'A reason.'; 45 | expectTypesEqual( 46 | buildInterface(generateInterfaceAST(), { fields: { field: { deprecationReason } } }), 47 | generateInterfaceType({ fields: { field: { type: GraphQLInt, deprecationReason } } }), 48 | ); 49 | }); 50 | 51 | it('should work with `resolveType` in config', () => { 52 | const config = { resolveType() {} }; 53 | expectTypesEqual(buildInterface(generateInterfaceAST(), config), generateInterfaceType(config)); 54 | }); 55 | }); 56 | -------------------------------------------------------------------------------- /src/build/__tests__/buildObject-test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | import { GraphQLObjectType, GraphQLInterfaceType, GraphQLInt } from 'graphql/type'; 4 | import { parse } from 'graphql/language'; 5 | import { expectTypesEqual } from './comparators'; 6 | import buildObject from '../buildObject'; 7 | 8 | describe('buildObject()', () => { 9 | const generateObjectAST = ({ 10 | description, 11 | name = 'Object', 12 | interfaces = [], 13 | fields = { field: 'Int' }, 14 | } = {}) => parse(` 15 | # ${description === undefined ? '' : description} 16 | type ${name} ${interfaces.length ? `implements ${interfaces.join(', ')}` : ''} { 17 | ${Object.entries(fields).map((entry) => entry.join(': ')).join('\n')} 18 | } 19 | `).definitions[0]; 20 | const generateObjectType = ({ 21 | name = 'Object', 22 | interfaces, 23 | fields = { field: { type: GraphQLInt } }, 24 | isTypeOf, 25 | description, 26 | } = {}) => new GraphQLObjectType({ name, interfaces, fields, isTypeOf, description }); 27 | 28 | it('should work with minimal AST', () => { 29 | expectTypesEqual(buildObject(generateObjectAST()), generateObjectType()); 30 | }); 31 | 32 | it('should work with description in AST', () => { 33 | const config = { description: 'A description.' }; 34 | expectTypesEqual(buildObject(generateObjectAST(config)), generateObjectType(config)); 35 | }); 36 | 37 | it('should work with interfaces in AST', () => { 38 | const Interface = new GraphQLInterfaceType({ name: 'Interface', resolveType() {} }); 39 | expectTypesEqual( 40 | buildObject(generateObjectAST({ interfaces: ['Interface'] }), undefined, [Interface]), 41 | generateObjectType({ interfaces: [Interface] }), 42 | ); 43 | }); 44 | 45 | it('should work with `resolve` shortcut', () => { 46 | const resolve = () => {}; 47 | expectTypesEqual( 48 | buildObject(generateObjectAST(), { field: resolve }), 49 | generateObjectType({ fields: { field: { type: GraphQLInt, resolve } } }), 50 | ); 51 | }); 52 | 53 | it('should work with `fields` in config', () => { 54 | const deprecationReason = 'A reason.'; 55 | expectTypesEqual( 56 | buildObject(generateObjectAST(), { fields: { field: { deprecationReason } } }), 57 | generateObjectType({ fields: { field: { type: GraphQLInt, deprecationReason } } }), 58 | ); 59 | }); 60 | 61 | it('should work with `isTypeOf` in config', () => { 62 | const config = { isTypeOf() {} }; 63 | expectTypesEqual(buildObject(generateObjectAST(), config), generateObjectType(config)); 64 | }); 65 | }); 66 | -------------------------------------------------------------------------------- /src/build/__tests__/buildScalar-test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | import { GraphQLScalarType } from 'graphql/type'; 4 | import { parse } from 'graphql/language'; 5 | import buildScalar from '../buildScalar'; 6 | 7 | describe('buildScalar()', () => { 8 | const generateScalarAST = ({ description, name = 'Scalar' } = {}) => parse(` 9 | # ${description === undefined ? '' : description} 10 | scalar ${name} 11 | `).definitions[0]; 12 | const generateScalarType = ({ 13 | name = 'Scalar', 14 | description, 15 | serialize, 16 | parseValue, 17 | parseLiteral, 18 | } = {}) => new GraphQLScalarType({ name, description, serialize, parseValue, parseLiteral }); 19 | 20 | it('should throw with without `serialize` in config', () => { 21 | expect(() => buildScalar(generateScalarAST())).toThrow(); 22 | }); 23 | 24 | it('should work with `serialize` in config', () => { 25 | const config = { serialize() {} }; 26 | expect(buildScalar(generateScalarAST(), config)).toEqual(generateScalarType(config)); 27 | }); 28 | 29 | it('should work with `serialize` in config and description in AST', () => { 30 | const config = { description: 'A description', serialize() {} }; 31 | expect(buildScalar(generateScalarAST(config), config)).toEqual(generateScalarType(config)); 32 | }); 33 | 34 | it('should work with `serialize`, `parseValue`, and `parseLiteral` in config', () => { 35 | const config = { serialize() {}, parseValue() {}, parseLiteral() {} }; 36 | expect(buildScalar(generateScalarAST(), config)).toEqual(generateScalarType(config)); 37 | }); 38 | 39 | it('should work with GraphQL scalar type', () => { 40 | const config = { serialize() {} }; 41 | expect(buildScalar(generateScalarAST(), generateScalarType(config))) 42 | .toEqual(generateScalarType(config)); 43 | }); 44 | }); 45 | -------------------------------------------------------------------------------- /src/build/__tests__/buildSchema-test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | import { GraphQLSchema, GraphQLObjectType, GraphQLInt } from 'graphql/type'; 4 | import { parse } from 'graphql/language'; 5 | import buildSchema, { buildOperation } from '../buildSchema'; 6 | 7 | const generateSchemaAST = ({ query = 'Query', mutation, subscription } = {}) => parse(` 8 | schema { 9 | ${query == null ? '' : `query: ${query}`} 10 | ${mutation === undefined ? '' : `mutation: ${mutation}`} 11 | ${subscription === undefined ? '' : `subscription: ${subscription}`} 12 | } 13 | `).definitions[0]; 14 | const generateObjectType = (name) => new GraphQLObjectType({ 15 | name, 16 | fields: { field: { type: GraphQLInt } }, 17 | }); 18 | const typeDependencies = [generateObjectType('Query')]; 19 | 20 | describe('buildOperation()', () => { 21 | it('should work', () => { 22 | expect(buildOperation(generateSchemaAST(), 'query', typeDependencies)); 23 | }); 24 | }); 25 | 26 | describe('buildSchema()', () => { 27 | const generateSchema = ({ 28 | query = generateObjectType('Query'), 29 | mutation, 30 | subscription, 31 | types, 32 | directives, 33 | } = {}) => new GraphQLSchema({ query, mutation, subscription, types, directives }); 34 | 35 | it('should throw without query in AST', () => { 36 | const Mutation = generateObjectType('Mutation'); 37 | const Subscription = generateObjectType('Subscription'); 38 | expect(() => buildSchema(generateSchemaAST({ 39 | query: null, mutation: Mutation.name, subscription: Subscription.name, 40 | }), undefined, [Mutation, Subscription])).toThrow(); 41 | }); 42 | 43 | it('should work with query in AST', () => { 44 | expect(buildSchema(generateSchemaAST(), undefined, typeDependencies)) 45 | .toEqual(generateSchema()); 46 | }); 47 | 48 | it('should work with query and mutation in AST', () => { 49 | const Mutation = generateObjectType('Mutation'); 50 | expect(buildSchema(generateSchemaAST({ 51 | mutation: Mutation.name, 52 | }), undefined, [...typeDependencies, Mutation])) 53 | .toEqual(generateSchema({ mutation: Mutation })); 54 | }); 55 | 56 | it('should work with query and subscription in AST', () => { 57 | const Subscription = generateObjectType('Subscription'); 58 | expect(buildSchema(generateSchemaAST({ 59 | subscription: Subscription.name, 60 | }), undefined, [...typeDependencies, Subscription])).toEqual(generateSchema({ 61 | subscription: Subscription, 62 | })); 63 | }); 64 | 65 | it('should work with `types` in config', () => { 66 | const config = { types: [] }; 67 | expect(buildSchema(generateSchemaAST(), config, typeDependencies)) 68 | .toEqual(generateSchema(config)); 69 | }); 70 | 71 | it('should work with `directives` in config', () => { 72 | const config = { directives: [] }; 73 | expect(buildSchema(generateSchemaAST(), config, typeDependencies)) 74 | .toEqual(generateSchema(config)); 75 | }); 76 | }); 77 | -------------------------------------------------------------------------------- /src/build/__tests__/buildUnion-test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | import { 4 | GraphQLUnionType, 5 | GraphQLInt, 6 | GraphQLFloat, 7 | GraphQLString, 8 | GraphQLBoolean, 9 | GraphQLID, 10 | } from 'graphql/type'; 11 | import { parse } from 'graphql/language'; 12 | import buildUnion from '../buildUnion'; 13 | 14 | describe('buildUnion()', () => { 15 | const generateUnionAST = ({ 16 | description, 17 | name = 'Union', 18 | types = 'Int | Float| String | Boolean | ID', 19 | } = {}) => parse(` 20 | # ${description === undefined ? '' : description} 21 | union ${name} = ${types} 22 | `).definitions[0]; 23 | const generateUnionType = ({ 24 | name = 'Union', 25 | types = [GraphQLInt, GraphQLFloat, GraphQLString, GraphQLBoolean, GraphQLID], 26 | resolveType, 27 | description, 28 | } = {}) => new GraphQLUnionType({ name, types, resolveType, description }); 29 | 30 | it('should work with minimal AST', () => { 31 | expect(buildUnion(generateUnionAST())).toEqual(generateUnionType()); 32 | }); 33 | 34 | it('should work with description in AST', () => { 35 | const config = { description: 'A description' }; 36 | expect(buildUnion(generateUnionAST(config))).toEqual(generateUnionType(config)); 37 | }); 38 | 39 | it('should work with `resolveType` in config', () => { 40 | const config = { resolveType() {} }; 41 | expect(buildUnion(generateUnionAST(), config)).toEqual(generateUnionType(config)); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /src/build/__tests__/comparators.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | export const expectTypesEqual = (a = {}, b = {}) => { 4 | expect(a.name).toBe(b.name); 5 | expect(a.description).toBe(b.description); 6 | expect(a.resolveType).toBe(b.resolveType); 7 | expect(a.isTypeOf).toBe(b.isTypeOf); 8 | expect(a.getFields && a.getFields()).toEqual(b.getFields && b.getFields()); 9 | expect(a.getInterfaces && a.getInterfaces()).toEqual(b.getInterfaces && b.getInterfaces()); 10 | }; 11 | 12 | export const expectSchemasEqual = (a, b) => { 13 | if (a.getQueryType) { 14 | if (b.getQueryType) expectTypesEqual(a.getQueryType(), b.getQueryType()); 15 | else expect(a.getQueryType).toEqual(b.getQueryType); 16 | } 17 | if (a.getMutationType) { 18 | if (b.getMutationType) expectTypesEqual(a.getMutationType(), b.getMutationType()); 19 | else expect(a.getMutationType).toEqual(b.getMutationType); 20 | } 21 | if (a.getSubscriptionType) { 22 | if (b.getSubscriptionType) expectTypesEqual(a.getSubscriptionType(), b.getSubscriptionType()); 23 | else expect(a.getSubscriptionType).toEqual(b.getSubscriptionType); 24 | } 25 | if (a.getTypeMap) { 26 | if (b.getTypeMap) { 27 | const aTypes = Object.values(a.getTypeMap()); 28 | Object.values(b.getTypeMap()).forEach((value, i) => expectTypesEqual(value, aTypes[i])); 29 | expectTypesEqual(a.getTypeMap(), b.getTypeMap()); 30 | } else expect(a.getTypeMap).toEqual(b.getTypeMap); 31 | } 32 | expect(a.getDirectives && a.getDirectives()).toEqual(b.getDirectives && b.getDirectives()); 33 | }; 34 | -------------------------------------------------------------------------------- /src/build/__tests__/produceType-test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | import { 4 | GraphQLScalarType, 5 | GraphQLInt, 6 | GraphQLFloat, 7 | GraphQLString, 8 | GraphQLBoolean, 9 | GraphQLID, 10 | GraphQLList, 11 | GraphQLNonNull, 12 | } from 'graphql/type'; 13 | import { parse } from 'graphql/language'; 14 | import produceType, { getNamedTypeAST, buildWrappedType } from '../produceType'; 15 | 16 | const [{ type: innerTypeAST }, { type: wrappedTypeAST }] = parse(` 17 | type Ints { 18 | int: Int 19 | nonNullListOfNonNullInt: [Int!]! 20 | } 21 | `, { noLocation: true }).definitions[0].fields; 22 | const wrappedType = new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLInt))); 23 | 24 | describe('getNamedTypeAST()', () => { 25 | it('should work', () => { 26 | expect(getNamedTypeAST(wrappedTypeAST)).toEqual(innerTypeAST); 27 | }); 28 | }); 29 | 30 | describe('buildWrappedType()', () => { 31 | it('should work', () => { 32 | expect(buildWrappedType(GraphQLInt, wrappedTypeAST)).toEqual(wrappedType); 33 | }); 34 | }); 35 | 36 | describe('produceType()', () => { 37 | const customTypeAST = parse(` 38 | scalar UUID 39 | `).definitions[0]; 40 | const UUID = new GraphQLScalarType({ name: 'UUID', serialize: String }); 41 | 42 | it('should produce GraphQL scalars', () => { 43 | const typeAST = parse(` 44 | type Scalars { 45 | int: Int 46 | float: Float 47 | string: String 48 | boolean: Boolean 49 | id: ID 50 | } 51 | `).definitions[0]; 52 | expect(typeAST.fields.map(({ type }) => type).map(produceType)) 53 | .toEqual([GraphQLInt, GraphQLFloat, GraphQLString, GraphQLBoolean, GraphQLID]); 54 | }); 55 | 56 | it('should produce GraphQL type wrappers', () => { 57 | expect(produceType(wrappedTypeAST, [])).toEqual(wrappedType); 58 | }); 59 | 60 | it('should produce custom types', () => { 61 | expect(produceType(customTypeAST, [UUID])).toEqual(UUID); 62 | }); 63 | 64 | it('should throw if it can\'t produce the type', () => { 65 | expect(() => produceType(customTypeAST, [])) 66 | .toThrowError('Type "UUID" not found.'); 67 | }); 68 | }); 69 | -------------------------------------------------------------------------------- /src/build/__tests__/resolveShortcut-test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | import resolveShortcut from '../resolveShortcut'; 4 | 5 | describe('resolveShortcut()', () => { 6 | it('should work', () => { 7 | const resolve = () => {}; 8 | expect(resolveShortcut({ field: resolve })).toEqual({ field: { resolve } }); 9 | }); 10 | }); 11 | -------------------------------------------------------------------------------- /src/build/__tests__/resolveThunk-test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | 3 | import resolveThunk from '../resolveThunk'; 4 | 5 | describe('resolveThunk()', () => { 6 | it('should work', () => { 7 | expect(resolveThunk(true)).toBe(true); 8 | expect(resolveThunk(() => true)).toBe(true); 9 | }); 10 | }); 11 | -------------------------------------------------------------------------------- /src/build/buildEnum.js: -------------------------------------------------------------------------------- 1 | import { GraphQLEnumType } from 'graphql/type'; 2 | import { getDescription } from 'graphql/utilities/buildASTSchema'; 3 | 4 | export const buildEnumValueConfigMap = (enumAST, configMap = {}) => 5 | enumAST.values.reduce((map, enumValueAST) => { 6 | const name = enumValueAST.name.value; 7 | const config = configMap[name] || {}; 8 | // set enum value to it's name by default 9 | const value = 'value' in config ? config.value : name; 10 | const description = getDescription(enumValueAST); 11 | const enumValueConfig = { value }; 12 | if ('deprecationReason' in config) enumValueConfig.deprecationReason = config.deprecationReason; 13 | if (description) enumValueConfig.description = description; 14 | return { ...map, [name]: enumValueConfig }; 15 | }, {}); 16 | 17 | export default function buildEnum(enumAST, { values } = {}) { 18 | const enumTypeConfig = { 19 | name: enumAST.name.value, 20 | values: buildEnumValueConfigMap(enumAST, values), 21 | }; 22 | const description = getDescription(enumAST); 23 | if (description) enumTypeConfig.description = description; 24 | return new GraphQLEnumType(enumTypeConfig); 25 | } 26 | -------------------------------------------------------------------------------- /src/build/buildFieldConfigMap.js: -------------------------------------------------------------------------------- 1 | import { getDescription } from 'graphql/utilities/buildASTSchema'; 2 | import { getNamedType } from 'graphql/type'; 3 | import produceType from './produceType'; 4 | 5 | export const buildFieldConfigArgumentMap = (fieldAST, types) => 6 | fieldAST.arguments.reduce((map, inputValueAST) => { 7 | const type = produceType(inputValueAST.type, types); 8 | const defaultValue = inputValueAST.defaultValue; 9 | const description = getDescription(inputValueAST); 10 | const argumentConfig = { type }; 11 | if (defaultValue !== null) { 12 | argumentConfig.defaultValue = getNamedType(type).parseLiteral(defaultValue); 13 | } 14 | if (description) argumentConfig.description = description; 15 | return { ...map, [inputValueAST.name.value]: argumentConfig }; 16 | }, {}); 17 | 18 | export default function buildFieldConfigMap(objectAST, configMap = {}, types) { 19 | return objectAST.fields.reduce((map, fieldAST) => { 20 | const name = fieldAST.name.value; 21 | const config = configMap[name] || {}; 22 | const type = produceType(fieldAST.type, types); 23 | const args = buildFieldConfigArgumentMap(fieldAST, types); 24 | const description = getDescription(fieldAST); 25 | const fieldConfig = { type }; 26 | if (Object.keys(args).length) fieldConfig.args = args; 27 | if ('resolve' in config) fieldConfig.resolve = config.resolve; 28 | if ('deprecationReason' in config) fieldConfig.deprecationReason = config.deprecationReason; 29 | if (description) fieldConfig.description = description; 30 | return { ...map, [name]: fieldConfig }; 31 | }, {}); 32 | } 33 | -------------------------------------------------------------------------------- /src/build/buildInputObject.js: -------------------------------------------------------------------------------- 1 | import { GraphQLInputObjectType, getNamedType } from 'graphql/type'; 2 | import { getDescription } from 'graphql/utilities/buildASTSchema'; 3 | import produceType from './produceType'; 4 | 5 | export const buildInputObjectConfigFieldMap = (inputObjectAST, types) => 6 | inputObjectAST.fields.reduce((map, inputValueAST) => { 7 | const name = inputValueAST.name.value; 8 | const type = produceType(inputValueAST.type, types); 9 | const defaultValue = inputValueAST.defaultValue; 10 | const description = getDescription(inputValueAST); 11 | const inputObjectFieldConfig = { type }; 12 | if (defaultValue !== null) { 13 | inputObjectFieldConfig.defaultValue = getNamedType(type).parseLiteral(defaultValue); 14 | } 15 | if (description) inputObjectFieldConfig.description = description; 16 | return { ...map, [name]: inputObjectFieldConfig }; 17 | }, {}); 18 | 19 | export default function buildInputObject(inputObjectAST, _, types) { 20 | const inputObjectTypeConfig = { 21 | name: inputObjectAST.name.value, 22 | fields: () => buildInputObjectConfigFieldMap(inputObjectAST, types), 23 | }; 24 | const description = getDescription(inputObjectAST); 25 | if (description) inputObjectTypeConfig.description = description; 26 | return new GraphQLInputObjectType(inputObjectTypeConfig); 27 | } 28 | -------------------------------------------------------------------------------- /src/build/buildInterface.js: -------------------------------------------------------------------------------- 1 | import { GraphQLInterfaceType } from 'graphql/type'; 2 | import { getDescription } from 'graphql/utilities/buildASTSchema'; 3 | import buildFieldConfigMap from './buildFieldConfigMap'; 4 | import resolveShortcut from './resolveShortcut'; 5 | 6 | export default function buildInterface(interfaceAST, config = {}, types) { 7 | const interfaceTypeConfig = { name: interfaceAST.name.value }; 8 | const description = getDescription(interfaceAST); 9 | if (!('fields' in config) && !('resolveType' in config)) { 10 | // `resolve` shortcut 11 | interfaceTypeConfig.fields = () => 12 | buildFieldConfigMap(interfaceAST, resolveShortcut(config), types); 13 | } else { 14 | interfaceTypeConfig.fields = () => buildFieldConfigMap(interfaceAST, config.fields, types); 15 | interfaceTypeConfig.resolveType = config.resolveType; 16 | } 17 | if (description) interfaceTypeConfig.description = description; 18 | return new GraphQLInterfaceType(interfaceTypeConfig); 19 | } 20 | -------------------------------------------------------------------------------- /src/build/buildObject.js: -------------------------------------------------------------------------------- 1 | import { GraphQLObjectType } from 'graphql/type'; 2 | import { getDescription } from 'graphql/utilities/buildASTSchema'; 3 | import produceType from './produceType'; 4 | import buildFieldConfigMap from './buildFieldConfigMap'; 5 | import resolveShortcut from './resolveShortcut'; 6 | 7 | export default function buildObject(objectAST, config = {}, types) { 8 | const objectTypeConfig = { name: objectAST.name.value }; 9 | const interfaces = objectAST.interfaces; 10 | const description = getDescription(objectAST); 11 | if (interfaces.length) { 12 | objectTypeConfig.interfaces = () => interfaces.map((typeAST) => produceType(typeAST, types)); 13 | } 14 | if (!('fields' in config) && !('isTypeOf' in config)) { 15 | // `resolve` shortcut 16 | objectTypeConfig.fields = () => buildFieldConfigMap(objectAST, resolveShortcut(config), types); 17 | } else { 18 | objectTypeConfig.fields = () => buildFieldConfigMap(objectAST, config.fields, types); 19 | objectTypeConfig.isTypeOf = config.isTypeOf; 20 | } 21 | if (description) objectTypeConfig.description = description; 22 | return new GraphQLObjectType(objectTypeConfig); 23 | } 24 | -------------------------------------------------------------------------------- /src/build/buildScalar.js: -------------------------------------------------------------------------------- 1 | import { GraphQLScalarType } from 'graphql/type'; 2 | import { getDescription } from 'graphql/utilities/buildASTSchema'; 3 | 4 | export default function buildScalar(scalarAST, config = {}) { 5 | const { 6 | serialize, 7 | parseValue, 8 | parseLiteral, 9 | // eslint-disable-next-line no-underscore-dangle 10 | } = config instanceof GraphQLScalarType ? config._scalarConfig : config; 11 | const scalarTypeConfig = { name: scalarAST.name.value, serialize, parseValue, parseLiteral }; 12 | const description = getDescription(scalarAST); 13 | if (description) scalarTypeConfig.description = description; 14 | return new GraphQLScalarType(scalarTypeConfig); 15 | } 16 | -------------------------------------------------------------------------------- /src/build/buildSchema.js: -------------------------------------------------------------------------------- 1 | import { GraphQLSchema } from 'graphql/type'; 2 | import produceType from './produceType'; 3 | 4 | export const buildOperation = (schemaAST, operation, types) => { 5 | const operationAST = schemaAST.operationTypes.find((ast) => ast.operation === operation); 6 | return operationAST && produceType(operationAST.type, types); 7 | }; 8 | 9 | export default function buildSchema(schemaAST, { types, directives } = {}, typeDeps) { 10 | const query = buildOperation(schemaAST, 'query', typeDeps); 11 | const mutation = buildOperation(schemaAST, 'mutation', typeDeps); 12 | const subscription = buildOperation(schemaAST, 'subscription', typeDeps); 13 | const schemaConfig = { types, directives }; 14 | if (query) schemaConfig.query = query; 15 | if (mutation) schemaConfig.mutation = mutation; 16 | if (subscription) schemaConfig.subscription = subscription; 17 | return new GraphQLSchema(schemaConfig); 18 | } 19 | -------------------------------------------------------------------------------- /src/build/buildUnion.js: -------------------------------------------------------------------------------- 1 | import { GraphQLUnionType } from 'graphql/type'; 2 | import { getDescription } from 'graphql/utilities/buildASTSchema'; 3 | import produceType from './produceType'; 4 | 5 | export default function buildUnion(unionAST, { resolveType } = {}, types) { 6 | const unionTypeConfig = { 7 | name: unionAST.name.value, 8 | types: unionAST.types.map((typeAST) => produceType(typeAST, types)), 9 | resolveType, 10 | }; 11 | const description = getDescription(unionAST); 12 | if (description) unionTypeConfig.description = description; 13 | return new GraphQLUnionType(unionTypeConfig); 14 | } 15 | -------------------------------------------------------------------------------- /src/build/index.js: -------------------------------------------------------------------------------- 1 | import { GraphQLSchema } from 'graphql/type'; 2 | import { Kind, parse } from 'graphql/language'; 3 | import buildSchema from './buildSchema'; 4 | import buildScalar from './buildScalar'; 5 | import buildObject from './buildObject'; 6 | import buildInterface from './buildInterface'; 7 | import buildUnion from './buildUnion'; 8 | import buildEnum from './buildEnum'; 9 | import buildInputObject from './buildInputObject'; 10 | import resolveThunk from './resolveThunk'; 11 | 12 | const buildMap = { 13 | [Kind.SCALAR_TYPE_DEFINITION]: buildScalar, 14 | [Kind.OBJECT_TYPE_DEFINITION]: buildObject, 15 | [Kind.INTERFACE_TYPE_DEFINITION]: buildInterface, 16 | [Kind.UNION_TYPE_DEFINITION]: buildUnion, 17 | [Kind.ENUM_TYPE_DEFINITION]: buildEnum, 18 | [Kind.INPUT_OBJECT_TYPE_DEFINITION]: buildInputObject, 19 | }; 20 | 21 | export const SCHEMA_CONFIG_KEY = '__schema'; 22 | 23 | export const ensureNoDuplicateTypes = (types) => { 24 | types.forEach((typeA) => { 25 | if (types.some((typeB) => typeA !== typeB && typeA.name === typeB.name)) { 26 | throw new Error(`Duplicate type "${typeA.name}" in schema definition or type dependencies.`); 27 | } 28 | }); 29 | return types; 30 | }; 31 | 32 | export const buildTypes = (documentAST, configMap = {}, typeDependencies = []) => { 33 | const derived = documentAST.definitions.map((definition) => { 34 | const buildDefinition = buildMap[definition.kind]; 35 | if (!buildDefinition) return false; 36 | return buildDefinition( 37 | definition, 38 | configMap[definition.name.value], 39 | () => ensureNoDuplicateTypes([...derived, ...resolveThunk(typeDependencies)]), 40 | ); 41 | }).filter((x) => x); 42 | return derived; 43 | }; 44 | 45 | export default function build(source, config = {}, typeDeps = [], infer = true) { 46 | if (typeof source !== 'string') throw new Error(`Expected a string but got ${source}.`); 47 | 48 | /* eslint-disable no-param-reassign */ 49 | if (Array.isArray(config) || typeof config === 'function') { 50 | infer = typeof typeDeps === 'boolean' ? typeDeps : true; 51 | typeDeps = config; 52 | config = {}; 53 | } 54 | 55 | if (typeof config === 'boolean') { 56 | infer = config; 57 | typeDeps = []; 58 | config = {}; 59 | } 60 | 61 | if (typeof typeDeps === 'boolean') { 62 | infer = typeDeps; 63 | typeDeps = []; 64 | } 65 | /* eslint-enable no-param-reassign */ 66 | 67 | if (!(config instanceof Object)) throw new Error(`Expected an object but got ${config}.`); 68 | if (!(Array.isArray(typeDeps) || typeof typeDeps === 'function')) { 69 | throw new Error(`Expected an array or a function but got ${typeDeps}.`); 70 | } 71 | if (typeof infer !== 'boolean') throw new Error(`Expected a boolean but got ${infer}.`); 72 | 73 | const documentAST = parse(source); 74 | const { definitions } = documentAST; 75 | const firstDefinition = definitions[0]; 76 | const shouldReturnOneType = ( 77 | definitions.length === 1 && 78 | ~Object.keys(buildMap).indexOf(firstDefinition.kind) && 79 | !(firstDefinition.name.value === 'Query' && infer) 80 | ); 81 | const types = ensureNoDuplicateTypes(buildTypes( 82 | documentAST, 83 | shouldReturnOneType ? { [firstDefinition.name.value]: config } : config, 84 | typeDeps, 85 | )); 86 | 87 | if (shouldReturnOneType) return types[0]; 88 | 89 | // try to build the defined schema 90 | const schemaASTs = definitions.filter(({ kind }) => kind === Kind.SCHEMA_DEFINITION); 91 | if (schemaASTs.length > 1) throw new Error('Must provide only one schema definition.'); 92 | if (schemaASTs.length === 1) { 93 | if (!Array.isArray(typeDeps)) { 94 | throw new Error('Can\'t use thunks as type dependencies for schema.'); 95 | } 96 | return buildSchema( 97 | schemaASTs[0], 98 | config[SCHEMA_CONFIG_KEY], 99 | () => ensureNoDuplicateTypes([...types, ...typeDeps]), 100 | ); 101 | } 102 | 103 | // try to build an inferred schema 104 | if (infer) { 105 | const QueryType = types.find(({ name }) => name === 'Query'); 106 | if (QueryType) { 107 | if (!Array.isArray(typeDeps)) { 108 | throw new Error('Can\'t use thunks as type dependencies for schema.'); 109 | } 110 | const allTypes = ensureNoDuplicateTypes([...types, ...typeDeps]); 111 | return new GraphQLSchema({ 112 | query: QueryType, 113 | mutation: allTypes.find(({ name }) => name === 'Mutation'), 114 | subscription: allTypes.find(({ name }) => name === 'Subscription'), 115 | }); 116 | } 117 | } 118 | 119 | // return a type map 120 | return types.reduce((map, type) => ({ ...map, [type.name]: type }), {}); 121 | } 122 | -------------------------------------------------------------------------------- /src/build/produceType.js: -------------------------------------------------------------------------------- 1 | import { 2 | GraphQLInt, 3 | GraphQLFloat, 4 | GraphQLString, 5 | GraphQLBoolean, 6 | GraphQLID, 7 | GraphQLList, 8 | GraphQLNonNull, 9 | } from 'graphql/type'; 10 | import { Kind } from 'graphql/language'; 11 | import resolveThunk from './resolveThunk'; 12 | 13 | const { LIST_TYPE, NON_NULL_TYPE } = Kind; 14 | 15 | const scalarTypeMap = { 16 | Int: GraphQLInt, 17 | Float: GraphQLFloat, 18 | String: GraphQLString, 19 | Boolean: GraphQLBoolean, 20 | ID: GraphQLID, 21 | }; 22 | 23 | export const getNamedTypeAST = (typeAST) => { 24 | let namedTypeAST = typeAST; 25 | while (namedTypeAST.kind === LIST_TYPE || namedTypeAST.kind === NON_NULL_TYPE) { 26 | namedTypeAST = namedTypeAST.type; 27 | } 28 | return namedTypeAST; 29 | }; 30 | 31 | export const buildWrappedType = (innerType, typeAST) => { 32 | if (typeAST.kind === LIST_TYPE) { 33 | return new GraphQLList(buildWrappedType(innerType, typeAST.type)); 34 | } 35 | if (typeAST.kind === NON_NULL_TYPE) { 36 | return new GraphQLNonNull(buildWrappedType(innerType, typeAST.type)); 37 | } 38 | return innerType; 39 | }; 40 | 41 | export default function produceType(typeAST, types) { 42 | const namedTypeAST = getNamedTypeAST(typeAST); 43 | const typeName = namedTypeAST.name.value; 44 | if (scalarTypeMap[typeName]) return buildWrappedType(scalarTypeMap[typeName], typeAST); 45 | const maybeType = resolveThunk(types).find(({ name }) => name === typeName); 46 | if (maybeType) return buildWrappedType(maybeType, typeAST); 47 | throw new Error(`Type "${typeName}" not found.`); 48 | } 49 | -------------------------------------------------------------------------------- /src/build/resolveShortcut.js: -------------------------------------------------------------------------------- 1 | export default function resolveShortcut(resolveMap) { 2 | return Object.keys(resolveMap).reduce((map, fieldName) => ({ 3 | ...map, [fieldName]: { resolve: resolveMap[fieldName] }, 4 | }), {}); 5 | } 6 | -------------------------------------------------------------------------------- /src/build/resolveThunk.js: -------------------------------------------------------------------------------- 1 | export default function resolveThunk(thunk) { 2 | return typeof thunk === 'function' ? thunk() : thunk; 3 | } 4 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import build from './build'; 2 | 3 | export { build }; // eslint-disable-line import/prefer-default-export 4 | --------------------------------------------------------------------------------