├── .eslintignore ├── AUTHORS ├── .npmignore ├── .prettierrc ├── tsconfig.build.json ├── src ├── index.ts ├── __fixtures__ │ ├── Schema.ts │ ├── app.ts │ ├── People.ts │ └── Film.ts ├── InputObjectParser.ts ├── ObjectParser.ts └── __tests__ │ ├── ObjectParser-test.ts │ ├── InputObjectParser-test.ts │ └── composeWithJson-test.ts ├── CHANGELOG.md ├── jest.config.js ├── .vscode ├── settings.json ├── tasks.json └── launch.json ├── .github ├── FUNDING.yml └── workflows │ └── nodejs.yml ├── .gitignore ├── tsconfig.json ├── LICENSE.md ├── .eslintrc.js ├── package.json └── README.md /.eslintignore: -------------------------------------------------------------------------------- 1 | lib/* 2 | flow-typed 3 | mjs/* 4 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Pavel Chertorogov -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.log 3 | src 4 | __fixtures__ 5 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "arrowParens": "always", 4 | "tabWidth": 2, 5 | "useTabs": false, 6 | "printWidth": 100, 7 | "trailingComma": "es5" 8 | } -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "types": ["node"], 5 | "outDir": "./lib", 6 | }, 7 | "include": ["src/**/*"], 8 | "exclude": ["**/__tests__", "**/__mocks__"] 9 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import ObjectParser from './ObjectParser'; 2 | import InputObjectParser from './InputObjectParser'; 3 | 4 | const composeWithJson = ObjectParser.createTC.bind(ObjectParser); 5 | const composeInputWithJson = InputObjectParser.createITC.bind(InputObjectParser); 6 | 7 | export default composeWithJson; 8 | export { composeWithJson, composeInputWithJson }; 9 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## master 2 | 3 | ## 0.0.0-semantically-released (October 24, 2017) 4 | This package publishing automated by [semantic-release](https://github.com/semantic-release/semantic-release). 5 | [Changelog](https://github.com/graphql-compose/graphql-compose-json/releases) is generated automatically and can be found here: https://github.com/graphql-compose/graphql-compose-json/releases 6 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest', 3 | globals: { 4 | 'ts-jest': { 5 | tsConfig: '/tsconfig.json', 6 | isolatedModules: true, 7 | diagnostics: false, 8 | }, 9 | }, 10 | moduleFileExtensions: ['ts', 'js'], 11 | transform: { 12 | '^.+\\.ts$': 'ts-jest', 13 | }, 14 | roots: ['/src'], 15 | testPathIgnorePatterns: ['/node_modules/', '/lib/'], 16 | testMatch: ['**/__tests__/**/*-test.(ts|js)'], 17 | }; 18 | -------------------------------------------------------------------------------- /src/__fixtures__/Schema.ts: -------------------------------------------------------------------------------- 1 | import { schemaComposer } from 'graphql-compose'; 2 | import { FilmTC } from './Film'; 3 | import { PeopleTC } from './People'; 4 | 5 | schemaComposer.Query.addFields({ 6 | film: FilmTC.getResolver('findById'), 7 | people: PeopleTC.getResolver('findById'), 8 | peopleByUrl: PeopleTC.getResolver('findByUrl'), 9 | peopleByUrls: PeopleTC.getResolver('findByUrlList'), 10 | }); 11 | 12 | const schema = schemaComposer.buildSchema(); 13 | 14 | export default schema; 15 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "javascript.validate.enable": false, 3 | "eslint.validate": [ 4 | { "language": "javascript", "autoFix": true }, 5 | { "language": "javascriptreact", "autoFix": true }, 6 | { "language": "typescript", "autoFix": true }, 7 | { "language": "typescriptreact", "autoFix": true } 8 | ], 9 | "typescript.tsdk": "node_modules/typescript/lib", 10 | "editor.codeActionsOnSave": { 11 | "source.fixAll.eslint": true 12 | }, 13 | "eslint.autoFixOnSave": true, 14 | } 15 | -------------------------------------------------------------------------------- /src/__fixtures__/app.ts: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import { graphqlHTTP } from 'express-graphql'; 3 | import schema from './Schema'; 4 | 5 | const PORT = 4000; 6 | const app = express(); 7 | 8 | app.use( 9 | '/graphql', 10 | graphqlHTTP((req) => ({ 11 | schema, 12 | graphiql: true, 13 | context: req, 14 | })) 15 | ); 16 | 17 | app.listen(PORT, () => { 18 | console.log(`App running on port ${PORT}`); //eslint-disable-line 19 | console.log(`Open http://localhost:${PORT}/graphql`); //eslint-disable-line 20 | }); 21 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [nodkz] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: graphql-compose 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "label": "Eslint checks", 8 | "type": "shell", 9 | "command": "./node_modules/.bin/eslint 'packages/*/src/**/*.{js,ts,tsx}'", 10 | "problemMatcher": ["$eslint-stylish"], 11 | "isBackground": true, 12 | "presentation": { 13 | "reveal": "never" 14 | }, 15 | "runOptions": { 16 | "reevaluateOnRerun": true, 17 | "runOn": "folderOpen" 18 | }, 19 | "group": { 20 | "kind": "build", 21 | "isDefault": true 22 | } 23 | } 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | 15 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 16 | .grunt 17 | 18 | # node-waf configuration 19 | .lock-wscript 20 | 21 | # Compiled binary addons (http://nodejs.org/api/addons.html) 22 | build/Release 23 | 24 | # IntelliJ Files 25 | *.iml 26 | *.ipr 27 | *.iws 28 | /out/ 29 | .idea/ 30 | .idea_modules/ 31 | 32 | # Dependency directory 33 | node_modules 34 | 35 | # Optional npm cache directory 36 | .npm 37 | 38 | # Optional REPL history 39 | .node_repl_history 40 | 41 | # Transpiled code 42 | /es 43 | /lib 44 | /mjs 45 | 46 | coverage 47 | .nyc_output 48 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2016", 4 | "module": "commonjs", 5 | "moduleResolution": "node", 6 | "esModuleInterop": true, 7 | "sourceMap": true, 8 | "declaration": true, 9 | "declarationMap": true, 10 | "removeComments": true, 11 | "strict": true, 12 | "noImplicitAny": true, 13 | "noImplicitReturns": true, 14 | "noFallthroughCasesInSwitch": true, 15 | "noUnusedParameters": true, 16 | "noUnusedLocals": true, 17 | "forceConsistentCasingInFileNames": true, 18 | "lib": ["es2017", "esnext.asynciterable"], 19 | "types": ["node", "jest"], 20 | "baseUrl": ".", 21 | "paths": { 22 | "*" : ["types/*"] 23 | }, 24 | "rootDir": "./src", 25 | }, 26 | "include": ["src/**/*"], 27 | "exclude": [ 28 | "./node_modules" 29 | ] 30 | } 31 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017-present 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Jest Current File", 9 | "type": "node", 10 | "request": "launch", 11 | "program": "${workspaceFolder}/node_modules/.bin/jest", 12 | "args": ["${fileBasenameNoExtension}", "--config", "jest.config.js"], 13 | "console": "integratedTerminal", 14 | "internalConsoleOptions": "neverOpen", 15 | "runtimeArgs": ["--nolazy"], // tells v8 to compile your code ahead of time, so that breakpoints work correctly 16 | "disableOptimisticBPs": true // also helps that breakpoints work correctly 17 | }, 18 | { 19 | "name": "Jest", 20 | "type": "node", 21 | "request": "launch", 22 | "program": "${workspaceFolder}/node_modules/.bin/jest", 23 | "args": ["--runInBand", "--watch"], 24 | "cwd": "${workspaceFolder}", 25 | "console": "integratedTerminal", 26 | "internalConsoleOptions": "neverOpen", 27 | "disableOptimisticBPs": true 28 | } 29 | ] 30 | } 31 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = { 4 | parser: '@typescript-eslint/parser', 5 | plugins: ['@typescript-eslint', 'prettier'], 6 | extends: ['plugin:@typescript-eslint/recommended', 'prettier', 'plugin:prettier/recommended'], 7 | parserOptions: { 8 | sourceType: 'module', 9 | useJSXTextNode: true, 10 | project: [path.resolve(__dirname, 'tsconfig.json')], 11 | }, 12 | rules: { 13 | 'no-underscore-dangle': 0, 14 | 'arrow-body-style': 0, 15 | 'no-unused-expressions': 0, 16 | 'no-plusplus': 0, 17 | 'no-console': 0, 18 | 'func-names': 0, 19 | 'comma-dangle': [ 20 | 'error', 21 | { 22 | arrays: 'always-multiline', 23 | objects: 'always-multiline', 24 | imports: 'always-multiline', 25 | exports: 'always-multiline', 26 | functions: 'ignore', 27 | }, 28 | ], 29 | 'no-prototype-builtins': 0, 30 | 'prefer-destructuring': 0, 31 | 'no-else-return': 0, 32 | 'lines-between-class-members': ['error', 'always', { exceptAfterSingleLine: true }], 33 | '@typescript-eslint/explicit-member-accessibility': 0, 34 | '@typescript-eslint/no-explicit-any': 0, 35 | '@typescript-eslint/no-inferrable-types': 0, 36 | '@typescript-eslint/explicit-function-return-type': 0, 37 | '@typescript-eslint/no-use-before-define': 0, 38 | '@typescript-eslint/no-empty-function': 0, 39 | '@typescript-eslint/camelcase': 0, 40 | }, 41 | env: { 42 | jasmine: true, 43 | jest: true, 44 | }, 45 | }; 46 | -------------------------------------------------------------------------------- /.github/workflows/nodejs.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: [push, pull_request] 7 | 8 | jobs: 9 | tests: 10 | runs-on: ubuntu-latest 11 | strategy: 12 | matrix: 13 | node-version: [12.x, 14.x, 16.x] 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: Use Node.js ${{ matrix.node-version }} 17 | uses: actions/setup-node@v1 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - name: Install node_modules 21 | run: yarn 22 | - name: Test & lint 23 | run: yarn test 24 | env: 25 | CI: true 26 | - name: Send codecov.io stats 27 | if: matrix.node-version == '12.x' 28 | run: bash <(curl -s https://codecov.io/bash) || echo '' 29 | 30 | publish: 31 | if: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/alpha' || github.ref == 'refs/heads/beta' 32 | needs: [tests] 33 | runs-on: ubuntu-latest 34 | steps: 35 | - uses: actions/checkout@v2 36 | - name: Use Node.js 12 37 | uses: actions/setup-node@v1 38 | with: 39 | node-version: 12.x 40 | - name: Install node_modules 41 | run: yarn install 42 | - name: Build 43 | run: yarn build 44 | - name: Semantic Release (publish to npm) 45 | run: yarn semantic-release 46 | env: 47 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 48 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 49 | 50 | -------------------------------------------------------------------------------- /src/__fixtures__/People.ts: -------------------------------------------------------------------------------- 1 | import fetch from 'node-fetch'; 2 | import { composeWithJson } from '../index'; 3 | import { FilmTC } from './Film'; 4 | import { ResolverResolveParams } from 'graphql-compose'; 5 | 6 | const restApiResponse = { 7 | name: 'Luke Skywalker', 8 | height: '172', 9 | mass: '77', 10 | hair_color: 'blond', 11 | skin_color: 'fair', 12 | eye_color: 'blue', 13 | birth_year: '19BBY', 14 | gender: 'male', 15 | films: [ 16 | 'https://swapi.co/api/films/2/', 17 | 'https://swapi.co/api/films/6/', 18 | 'https://swapi.co/api/films/3/', 19 | ], 20 | }; 21 | 22 | export const PeopleTC = composeWithJson('People', restApiResponse); 23 | 24 | // ////////////// 25 | // RESOLVERS aka FieldConfig in GraphQL 26 | // ////////////// 27 | 28 | PeopleTC.addResolver({ 29 | name: 'findById', 30 | type: PeopleTC, 31 | args: { 32 | id: 'Int!', 33 | }, 34 | resolve: (rp: ResolverResolveParams) => { 35 | return fetch(`https://swapi.co/api/people/${rp.args.id}/`).then((r) => r.json()); 36 | }, 37 | }); 38 | 39 | PeopleTC.addResolver({ 40 | name: 'findByUrl', 41 | type: PeopleTC, 42 | args: { 43 | url: 'String!', 44 | }, 45 | resolve: (rp: ResolverResolveParams) => fetch(rp.args.url).then((r) => r.json()), 46 | }); 47 | 48 | PeopleTC.addResolver({ 49 | name: 'findByUrlList', 50 | type: [PeopleTC], 51 | args: { 52 | urls: '[String]!', 53 | }, 54 | resolve: (rp: ResolverResolveParams) => { 55 | return Promise.all(rp.args.urls.map((url: string) => fetch(url).then((r) => r.json()))); 56 | }, 57 | }); 58 | 59 | // ////////////// 60 | // RELATIONS 61 | // ////////////// 62 | 63 | PeopleTC.addRelation('filmObjs', { 64 | resolver: () => FilmTC.getResolver('findByUrlList'), 65 | prepareArgs: { 66 | urls: (source) => source.films, 67 | }, 68 | }); 69 | -------------------------------------------------------------------------------- /src/__fixtures__/Film.ts: -------------------------------------------------------------------------------- 1 | import fetch from 'node-fetch'; 2 | import { composeWithJson } from '../index'; 3 | import { PeopleTC } from './People'; 4 | import { ResolverResolveParams } from 'graphql-compose'; 5 | 6 | const restApiResponse = { 7 | title: 'The Empire Strikes Back', 8 | episode_id: 5, 9 | opening_crawl: 'It is a dark time for ...', 10 | director: 'Irvin Kershner', 11 | producer: 'Gary Kurtz, Rick McCallum', 12 | release_date: '1980-05-17', 13 | characters: [ 14 | 'https://swapi.co/api/people/1/', 15 | 'https://swapi.co/api/people/2/', 16 | 'https://swapi.co/api/people/3/', 17 | ], 18 | }; 19 | 20 | export const FilmTC = composeWithJson('Film', restApiResponse); 21 | 22 | // ////////////// 23 | // RESOLVERS aka FieldConfig in GraphQL 24 | // ////////////// 25 | 26 | FilmTC.addResolver({ 27 | name: 'findById', 28 | type: FilmTC, 29 | args: { 30 | id: 'Int!', 31 | }, 32 | resolve: (rp: ResolverResolveParams) => { 33 | return fetch(`https://swapi.co/api/films/${rp.args.id}/`).then((r) => r.json()); 34 | }, 35 | }); 36 | 37 | FilmTC.addResolver({ 38 | name: 'findByUrl', 39 | type: FilmTC, 40 | args: { 41 | url: 'String!', 42 | }, 43 | resolve: (rp: ResolverResolveParams) => fetch(rp.args.url).then((r) => r.json()), 44 | }); 45 | 46 | FilmTC.addResolver({ 47 | name: 'findByUrlList', 48 | type: [FilmTC], 49 | args: { 50 | urls: '[String]!', 51 | }, 52 | resolve: (rp: ResolverResolveParams) => { 53 | return Promise.all(rp.args.urls.map((url: string) => fetch(url).then((r) => r.json()))); 54 | }, 55 | }); 56 | 57 | // ////////////// 58 | // RELATIONS 59 | // ////////////// 60 | 61 | FilmTC.addRelation('characters', { 62 | resolver: () => PeopleTC.getResolver('findByUrlList'), 63 | prepareArgs: { 64 | urls: (source) => source.characters, 65 | }, 66 | }); 67 | 68 | FilmTC.addFields({ 69 | currentTime: { type: 'String', resolve: () => Date.now() }, 70 | }); 71 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "graphql-compose-json", 3 | "version": "0.0.0-semantically-released", 4 | "description": "This is a plugin for `graphql-compose`, which generates GraphQLTypes from any JSON.", 5 | "files": [ 6 | "lib" 7 | ], 8 | "main": "lib/index.js", 9 | "types": "lib/index.d.ts", 10 | "repository": { 11 | "type": "git", 12 | "url": "https://github.com/graphql-compose/graphql-compose-json.git" 13 | }, 14 | "keywords": [ 15 | "graphql", 16 | "compose", 17 | "rest" 18 | ], 19 | "license": "MIT", 20 | "bugs": { 21 | "url": "https://github.com/graphql-compose/graphql-compose-json/issues" 22 | }, 23 | "homepage": "https://github.com/graphql-compose/graphql-compose-json", 24 | "peerDependencies": { 25 | "graphql-compose": "^7.0.4 || ^8.0.0 || ^9.0.0" 26 | }, 27 | "devDependencies": { 28 | "@types/express": "4.17.12", 29 | "@types/express-graphql": "^0.9.0", 30 | "@types/jest": "26.0.23", 31 | "@types/node": "15.6.1", 32 | "@types/node-fetch": "2.5.10", 33 | "@typescript-eslint/eslint-plugin": "4.25.0", 34 | "@typescript-eslint/parser": "4.25.0", 35 | "cross-env": "7.0.3", 36 | "eslint": "7.27.0", 37 | "eslint-config-airbnb-base": "14.2.1", 38 | "eslint-config-prettier": "8.3.0", 39 | "eslint-plugin-import": "2.23.4", 40 | "eslint-plugin-prettier": "3.4.0", 41 | "express": "^4.17.1", 42 | "express-graphql": "0.12.0", 43 | "graphql": "15.5.0", 44 | "graphql-compose": "9.0.0", 45 | "jest": "27.0.3", 46 | "node-fetch": "2.6.1", 47 | "prettier": "2.3.0", 48 | "rimraf": "3.0.2", 49 | "semantic-release": "17.4.3", 50 | "ts-jest": "27.0.1", 51 | "ts-node": "10.0.0", 52 | "typescript": "4.3.2" 53 | }, 54 | "scripts": { 55 | "build": "rimraf lib && tsc -p ./tsconfig.build.json", 56 | "watch": "jest --watch", 57 | "coverage": "jest --coverage --maxWorkers 2", 58 | "lint": "yarn eslint && yarn tscheck", 59 | "eslint": "eslint --ext .ts ./src", 60 | "tscheck": "tsc --noEmit", 61 | "test": "cross-env NODE_ENV=test yarn coverage && yarn lint", 62 | "semantic-release": "semantic-release", 63 | "fixture-demo": "ts-node ./src/__fixtures__/app.ts" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/InputObjectParser.ts: -------------------------------------------------------------------------------- 1 | import { 2 | InputTypeComposer, 3 | upperFirst, 4 | InputTypeComposerFieldConfigDefinition, 5 | schemaComposer, 6 | SchemaComposer, 7 | isComposeInputType, 8 | } from 'graphql-compose'; 9 | 10 | type GetValueOpts = { 11 | typeName?: string; 12 | fieldName?: string; 13 | }; 14 | 15 | export default class InputObjectParser { 16 | static createITC( 17 | name: string, 18 | json: Record, 19 | opts?: { schemaComposer: SchemaComposer } 20 | ): InputTypeComposer { 21 | if (!json || typeof json !== 'object') { 22 | throw new Error('You provide empty object in second arg for `createITC` method.'); 23 | } 24 | 25 | const sc = opts?.schemaComposer || schemaComposer; 26 | 27 | const tc = sc.createInputTC(name); 28 | Object.keys(json).forEach((fieldName) => { 29 | const fieldConfig = this.getFieldConfig(json[fieldName], { typeName: name, fieldName }); 30 | tc.setField(fieldName, fieldConfig); 31 | }); 32 | 33 | return tc; 34 | } 35 | 36 | static getFieldConfig( 37 | value: any, 38 | opts?: GetValueOpts | null 39 | ): InputTypeComposerFieldConfigDefinition { 40 | const typeOf = typeof value; 41 | 42 | if (typeOf === 'number') return 'Float'; 43 | if (typeOf === 'string') return 'String'; 44 | if (typeOf === 'boolean') return 'Boolean'; 45 | if (value instanceof Date) return 'Date'; 46 | 47 | if (isComposeInputType(value)) { 48 | return value; 49 | } 50 | 51 | if (typeOf === 'object') { 52 | if (value === null) return 'JSON'; 53 | 54 | if (Array.isArray(value)) { 55 | if (Array.isArray(value[0])) return ['JSON']; 56 | 57 | const val = 58 | typeof value[0] === 'object' && value[0] !== null 59 | ? Object.assign({}, ...value) 60 | : value[0]; 61 | 62 | const args = 63 | opts && opts.typeName && opts.fieldName 64 | ? { 65 | typeName: opts.typeName, 66 | fieldName: opts.fieldName, 67 | } 68 | : {}; 69 | return [this.getFieldConfig(val, args)] as any; 70 | } 71 | 72 | if (opts && opts.typeName && opts.fieldName) { 73 | return this.createITC(`${opts.typeName}_${upperFirst(opts.fieldName)}`, value); 74 | } 75 | } 76 | 77 | if (typeOf === 'function') { 78 | return value(); 79 | } 80 | return 'JSON'; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/ObjectParser.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ObjectTypeComposer, 3 | upperFirst, 4 | ObjectTypeComposerFieldConfigDefinition, 5 | schemaComposer, 6 | SchemaComposer, 7 | isComposeOutputType, 8 | } from 'graphql-compose'; 9 | 10 | type GetValueOpts = { 11 | typeName?: string; 12 | fieldName?: string; 13 | }; 14 | 15 | export default class ObjectParser { 16 | static createTC( 17 | name: string, 18 | json: Record, 19 | opts?: { schemaComposer: SchemaComposer } 20 | ): ObjectTypeComposer { 21 | if (!json || typeof json !== 'object') { 22 | throw new Error('You provide empty object in second arg for `createTC` method.'); 23 | } 24 | 25 | const sc = opts?.schemaComposer || schemaComposer; 26 | 27 | const tc = sc.createObjectTC(name); 28 | Object.keys(json).forEach((fieldName) => { 29 | const fieldConfig = this.getFieldConfig(json[fieldName], { typeName: name, fieldName }); 30 | tc.setField(fieldName, fieldConfig); 31 | }); 32 | 33 | return tc; 34 | } 35 | 36 | static getFieldConfig( 37 | value: any, 38 | opts?: GetValueOpts | null 39 | ): ObjectTypeComposerFieldConfigDefinition { 40 | const typeOf = typeof value; 41 | 42 | if (typeOf === 'number') return 'Float'; 43 | if (typeOf === 'string') return 'String'; 44 | if (typeOf === 'boolean') return 'Boolean'; 45 | if (value instanceof Date) return 'Date'; 46 | 47 | if (isComposeOutputType(value)) { 48 | return value; 49 | } 50 | 51 | if (typeOf === 'object') { 52 | if (value === null) return 'JSON'; 53 | 54 | if (Array.isArray(value)) { 55 | if (Array.isArray(value[0])) return ['JSON']; 56 | 57 | const val = 58 | typeof value[0] === 'object' && value[0] !== null 59 | ? Object.assign({}, ...value) 60 | : value[0]; 61 | 62 | const args = 63 | opts && opts.typeName && opts.fieldName 64 | ? { 65 | typeName: opts.typeName, 66 | fieldName: opts.fieldName, 67 | } 68 | : {}; 69 | return [this.getFieldConfig(val, args)] as any; 70 | } 71 | 72 | if (opts && opts.typeName && opts.fieldName) { 73 | return this.createTC(`${opts.typeName}_${upperFirst(opts.fieldName)}`, value); 74 | } 75 | } 76 | 77 | if (typeOf === 'function') { 78 | return value(); 79 | } 80 | return 'JSON'; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/__tests__/ObjectParser-test.ts: -------------------------------------------------------------------------------- 1 | import { ObjectTypeComposer, schemaComposer } from 'graphql-compose'; 2 | import OP from '../ObjectParser'; 3 | 4 | describe('ObjectParser', () => { 5 | describe('getFieldConfig()', () => { 6 | it('number', () => { 7 | expect(OP.getFieldConfig(6)).toBe('Float'); 8 | expect(OP.getFieldConfig(77.7)).toBe('Float'); 9 | }); 10 | 11 | it('string', () => { 12 | expect(OP.getFieldConfig('test')).toBe('String'); 13 | }); 14 | 15 | it('boolean', () => { 16 | expect(OP.getFieldConfig(true)).toBe('Boolean'); 17 | expect(OP.getFieldConfig(false)).toBe('Boolean'); 18 | }); 19 | 20 | it('null', () => { 21 | expect(OP.getFieldConfig(null)).toBe('JSON'); 22 | }); 23 | 24 | describe('array', () => { 25 | it('of number', () => { 26 | expect(OP.getFieldConfig([1, 2, 3])).toEqual(['Float']); 27 | }); 28 | 29 | it('of string', () => { 30 | expect(OP.getFieldConfig(['a', 'b', 'c'])).toEqual(['String']); 31 | }); 32 | 33 | it('of boolean', () => { 34 | expect(OP.getFieldConfig([false, true])).toEqual(['Boolean']); 35 | }); 36 | 37 | it('of object', () => { 38 | const spy = jest.spyOn(OP, 'createTC'); 39 | const valueAsArrayOfObjects = [{ a: 123 }, { a: 456 }]; 40 | OP.getFieldConfig(valueAsArrayOfObjects, { 41 | typeName: 'ParentTypeName', 42 | fieldName: 'subDocument', 43 | }); 44 | expect(spy).toHaveBeenCalledWith('ParentTypeName_SubDocument', { a: 456 }); 45 | }); 46 | 47 | it('of any', () => { 48 | expect(OP.getFieldConfig([null])).toEqual(['JSON']); 49 | }); 50 | }); 51 | 52 | it('function', () => { 53 | const valueAsFn = () => 'abracadabra'; 54 | const res = OP.getFieldConfig(valueAsFn); 55 | expect(res).toBe('abracadabra'); 56 | }); 57 | 58 | it('object', () => { 59 | const spy = jest.spyOn(OP, 'createTC'); 60 | const valueAsObj = { a: 123 }; 61 | OP.getFieldConfig(valueAsObj, { 62 | typeName: 'ParentTypeName', 63 | fieldName: 'subDocument', 64 | }); 65 | expect(spy).toHaveBeenCalledWith('ParentTypeName_SubDocument', valueAsObj); 66 | }); 67 | }); 68 | 69 | describe('createTC()', () => { 70 | it('return ObjectTypeComposer', () => { 71 | const tc = OP.createTC('MyType', { a: 1 }); 72 | expect(tc).toBeInstanceOf(ObjectTypeComposer); 73 | expect(tc.getTypeName()).toBe('MyType'); 74 | }); 75 | 76 | it('creates fields', () => { 77 | const tc = OP.createTC('MyType', { a: 1, b: true }); 78 | expect(tc.getFieldNames()).toEqual(['a', 'b']); 79 | expect(tc.getFieldTypeName('a')).toBe('Float'); 80 | expect(tc.getFieldTypeName('b')).toBe('Boolean'); 81 | }); 82 | 83 | it('match snapshot', () => { 84 | const PeopleTC = OP.createTC('PeopleType', { 85 | name: 'Luke Skywalker', 86 | height: () => 'Int', 87 | mass: () => 'Int', 88 | hair_color: 'blond', 89 | skin_color: 'fair', 90 | eye_color: 'blue', 91 | birth_year: '19BBY', 92 | gender: 'male', 93 | homeworld: { 94 | name: 'Tatooine', 95 | rotation_period: '23', 96 | orbital_period: '304', 97 | terrain: 'desert', 98 | surface_water: '1', 99 | population: () => 'Int', 100 | }, 101 | films: [ 102 | 'https://swapi.co/api/films/2/', 103 | 'https://swapi.co/api/films/6/', 104 | 'https://swapi.co/api/films/3/', 105 | ], 106 | created: () => 'Date', 107 | edited: '2014-12-20T21:17:56.891000Z', 108 | meta: schemaComposer.createObjectTC('type Meta { key: String, val: String }').List, 109 | }); 110 | 111 | expect(PeopleTC.toSDL({ deep: true, omitScalars: true })).toMatchInlineSnapshot(` 112 | "type PeopleType { 113 | name: String 114 | height: Int 115 | mass: Int 116 | hair_color: String 117 | skin_color: String 118 | eye_color: String 119 | birth_year: String 120 | gender: String 121 | homeworld: PeopleType_Homeworld 122 | films: [String] 123 | created: Date 124 | edited: String 125 | meta: [Meta] 126 | } 127 | 128 | type PeopleType_Homeworld { 129 | name: String 130 | rotation_period: String 131 | orbital_period: String 132 | terrain: String 133 | surface_water: String 134 | population: Int 135 | } 136 | 137 | type Meta { 138 | key: String 139 | val: String 140 | }" 141 | `); 142 | }); 143 | }); 144 | }); 145 | -------------------------------------------------------------------------------- /src/__tests__/InputObjectParser-test.ts: -------------------------------------------------------------------------------- 1 | import { InputTypeComposer, schemaComposer } from 'graphql-compose'; 2 | import IOP from '../InputObjectParser'; 3 | 4 | describe('InputObjectParser', () => { 5 | describe('getFieldConfig()', () => { 6 | it('number', () => { 7 | expect(IOP.getFieldConfig(6)).toBe('Float'); 8 | expect(IOP.getFieldConfig(77.7)).toBe('Float'); 9 | }); 10 | 11 | it('string', () => { 12 | expect(IOP.getFieldConfig('test')).toBe('String'); 13 | }); 14 | 15 | it('boolean', () => { 16 | expect(IOP.getFieldConfig(true)).toBe('Boolean'); 17 | expect(IOP.getFieldConfig(false)).toBe('Boolean'); 18 | }); 19 | 20 | it('null', () => { 21 | expect(IOP.getFieldConfig(null)).toBe('JSON'); 22 | }); 23 | 24 | describe('array', () => { 25 | it('of number', () => { 26 | expect(IOP.getFieldConfig([1, 2, 3])).toEqual(['Float']); 27 | }); 28 | 29 | it('of string', () => { 30 | expect(IOP.getFieldConfig(['a', 'b', 'c'])).toEqual(['String']); 31 | }); 32 | 33 | it('of boolean', () => { 34 | expect(IOP.getFieldConfig([false, true])).toEqual(['Boolean']); 35 | }); 36 | 37 | it('of object', () => { 38 | const spy = jest.spyOn(IOP, 'createITC'); 39 | const valueAsArrayOfObjects = [{ a: 123 }, { a: 456 }]; 40 | IOP.getFieldConfig(valueAsArrayOfObjects, { 41 | typeName: 'ParentTypeName', 42 | fieldName: 'subDocument', 43 | }); 44 | expect(spy).toHaveBeenCalledWith('ParentTypeName_SubDocument', { a: 456 }); 45 | }); 46 | 47 | it('of any', () => { 48 | expect(IOP.getFieldConfig([null])).toEqual(['JSON']); 49 | }); 50 | }); 51 | 52 | it('function', () => { 53 | const valueAsFn = () => 'abracadabra'; 54 | const res = IOP.getFieldConfig(valueAsFn); 55 | expect(res).toBe('abracadabra'); 56 | }); 57 | 58 | it('object', () => { 59 | const spy = jest.spyOn(IOP, 'createITC'); 60 | const valueAsObj = { a: 123 }; 61 | IOP.getFieldConfig(valueAsObj, { 62 | typeName: 'ParentTypeName', 63 | fieldName: 'subDocument', 64 | }); 65 | expect(spy).toHaveBeenCalledWith('ParentTypeName_SubDocument', valueAsObj); 66 | }); 67 | }); 68 | 69 | describe('createITC()', () => { 70 | it('return InputTypeComposer', () => { 71 | const tc = IOP.createITC('MyType', { a: 1 }); 72 | expect(tc).toBeInstanceOf(InputTypeComposer); 73 | expect(tc.getTypeName()).toBe('MyType'); 74 | }); 75 | 76 | it('creates fields', () => { 77 | const tc = IOP.createITC('MyType', { a: 1, b: true }); 78 | expect(tc.getFieldNames()).toEqual(['a', 'b']); 79 | expect(tc.getFieldTypeName('a')).toBe('Float'); 80 | expect(tc.getFieldTypeName('b')).toBe('Boolean'); 81 | }); 82 | 83 | it('match snapshot', () => { 84 | const PeopleITC = IOP.createITC('PeopleInput', { 85 | name: 'Luke Skywalker', 86 | height: () => 'Int', 87 | mass: () => 'Int', 88 | hair_color: 'blond', 89 | skin_color: 'fair', 90 | eye_color: schemaComposer.createEnumTC(`enum EyeColor { blue brown }`), 91 | birth_year: '19BBY', 92 | gender: 'male', 93 | homeworld: { 94 | name: 'Tatooine', 95 | rotation_period: '23', 96 | orbital_period: '304', 97 | terrain: 'desert', 98 | surface_water: '1', 99 | population: () => 'Int', 100 | }, 101 | films: [ 102 | 'https://swapi.co/api/films/2/', 103 | 'https://swapi.co/api/films/6/', 104 | 'https://swapi.co/api/films/3/', 105 | ], 106 | created: () => 'Date', 107 | edited: '2014-12-20T21:17:56.891000Z', 108 | filter: schemaComposer.createInputTC(`input FilterInput { name: String, mass: Int }`), 109 | }); 110 | 111 | expect(PeopleITC.toSDL({ deep: true, omitScalars: true })).toMatchInlineSnapshot(` 112 | "input PeopleInput { 113 | name: String 114 | height: Int 115 | mass: Int 116 | hair_color: String 117 | skin_color: String 118 | eye_color: EyeColor 119 | birth_year: String 120 | gender: String 121 | homeworld: PeopleInput_Homeworld 122 | films: [String] 123 | created: Date 124 | edited: String 125 | filter: FilterInput 126 | } 127 | 128 | enum EyeColor { 129 | blue 130 | brown 131 | } 132 | 133 | input PeopleInput_Homeworld { 134 | name: String 135 | rotation_period: String 136 | orbital_period: String 137 | terrain: String 138 | surface_water: String 139 | population: Int 140 | } 141 | 142 | input FilterInput { 143 | name: String 144 | mass: Int 145 | }" 146 | `); 147 | }); 148 | }); 149 | }); 150 | -------------------------------------------------------------------------------- /src/__tests__/composeWithJson-test.ts: -------------------------------------------------------------------------------- 1 | import fetch from 'node-fetch'; 2 | import { graphql } from 'graphql-compose'; 3 | import schema from '../__fixtures__/Schema'; 4 | import { PeopleTC } from '../__fixtures__/People'; 5 | import { composeWithJson } from '../index'; 6 | 7 | const { GraphQLSchema, GraphQLObjectType } = graphql; 8 | 9 | // There is a HEROKU problem with https://swapi.co 10 | // Disable tests temporary 11 | describe.skip('composeWithJson', () => { 12 | it('request film by id', async () => { 13 | const res = await graphql.graphql( 14 | schema, 15 | `{ 16 | film(id: 1) { 17 | title 18 | episode_id 19 | } 20 | }` 21 | ); 22 | expect(res).toEqual({ 23 | data: { film: { title: 'A New Hope', episode_id: 4 } }, 24 | }); 25 | }); 26 | 27 | it('request people with films', async () => { 28 | const res = await graphql.graphql( 29 | schema, 30 | `{ 31 | people(id: 1) { 32 | name 33 | films 34 | filmObjs { 35 | title 36 | } 37 | } 38 | }` 39 | ); 40 | expect(res).toEqual({ 41 | data: { 42 | people: { 43 | name: 'Luke Skywalker', 44 | filmObjs: [ 45 | { title: 'The Empire Strikes Back' }, 46 | { title: 'Revenge of the Sith' }, 47 | { title: 'Return of the Jedi' }, 48 | { title: 'A New Hope' }, 49 | { title: 'The Force Awakens' }, 50 | ], 51 | films: [ 52 | 'https://swapi.co/api/films/2/', 53 | 'https://swapi.co/api/films/6/', 54 | 'https://swapi.co/api/films/3/', 55 | 'https://swapi.co/api/films/1/', 56 | 'https://swapi.co/api/films/7/', 57 | ], 58 | }, 59 | }, 60 | }); 61 | }); 62 | 63 | it('allow set field config via function', async () => { 64 | const restApiResponse = { 65 | title: 'A New Hope', 66 | episode_id: 4, 67 | opening_crawl: 'It is a period of civil war of ... freedom to the galaxy....', 68 | director: 'George Lucas', 69 | producer: 'Gary Kurtz, Rick McCallum', 70 | release_date: '1977-05-25', 71 | // planets: [ 72 | // 'https://swapi.co/api/planets/2/', 73 | // 'https://swapi.co/api/planets/3/', 74 | // 'https://swapi.co/api/planets/1/' 75 | // ], 76 | planets: () => ({ 77 | type: 'Int', 78 | resolve: (source: any) => source.planets.length, 79 | }), 80 | // characters: [ 81 | // 'https://swapi.co/api/people/1/', 82 | // 'https://swapi.co/api/people/2/', 83 | // 'https://swapi.co/api/people/3/', 84 | // ], 85 | characters: () => 86 | PeopleTC.getResolver('findByUrlList') 87 | .wrapResolve((next) => (rp) => { 88 | const characterUrls = rp.source.characters; 89 | rp.args.urls = characterUrls; // eslint-disable-line 90 | return next(rp); 91 | }) 92 | .removeArg('urls'), 93 | }; 94 | 95 | const FilmTC = composeWithJson('FilmCustom', restApiResponse); 96 | 97 | const schema1 = new GraphQLSchema({ 98 | query: new GraphQLObjectType({ 99 | name: 'Query', 100 | fields: { 101 | film: { 102 | type: FilmTC.getType(), 103 | resolve: () => { 104 | return fetch(`https://swapi.co/api/films/1`).then((r) => r.json()); 105 | }, 106 | }, 107 | }, 108 | }), 109 | }); 110 | 111 | const res = await graphql.graphql( 112 | schema1, 113 | `{ 114 | film { 115 | title 116 | planets 117 | characters { 118 | name 119 | } 120 | } 121 | }` 122 | ); 123 | 124 | expect(res).toEqual({ 125 | data: { 126 | film: { 127 | title: 'A New Hope', 128 | planets: 3, 129 | characters: [ 130 | { name: 'Luke Skywalker' }, 131 | { name: 'C-3PO' }, 132 | { name: 'R2-D2' }, 133 | { name: 'Darth Vader' }, 134 | { name: 'Leia Organa' }, 135 | { name: 'Owen Lars' }, 136 | { name: 'Beru Whitesun lars' }, 137 | { name: 'R5-D4' }, 138 | { name: 'Biggs Darklighter' }, 139 | { name: 'Obi-Wan Kenobi' }, 140 | { name: 'Wilhuff Tarkin' }, 141 | { name: 'Chewbacca' }, 142 | { name: 'Han Solo' }, 143 | { name: 'Greedo' }, 144 | { name: 'Jabba Desilijic Tiure' }, 145 | { name: 'Wedge Antilles' }, 146 | { name: 'Jek Tono Porkins' }, 147 | { name: 'Raymus Antilles' }, 148 | ], 149 | }, 150 | }, 151 | }); 152 | }); 153 | 154 | it('check shallow objects', async () => { 155 | const restApiResponse = { 156 | title: 'A New Hope', 157 | producer: { 158 | name: 'Gary Kurtz, Rick McCallum', 159 | }, 160 | }; 161 | 162 | const FilmTC = composeWithJson('FilmCustom', restApiResponse); 163 | 164 | expect(FilmTC.getFieldTC('producer').getTypeName()).toBe('FilmCustom_Producer'); 165 | expect(FilmTC.getFieldOTC('producer').getFieldNames()).toEqual(['name']); 166 | expect(FilmTC.getFieldOTC('producer').getFieldTypeName('name')).toBe('String'); 167 | 168 | const schema1 = new GraphQLSchema({ 169 | query: new GraphQLObjectType({ 170 | name: 'Query', 171 | fields: { 172 | film: { 173 | type: FilmTC.getType(), 174 | resolve: () => { 175 | return restApiResponse; 176 | }, 177 | }, 178 | }, 179 | }), 180 | }); 181 | 182 | const res = await graphql.graphql( 183 | schema1, 184 | `{ 185 | film { 186 | title 187 | producer { 188 | name 189 | } 190 | } 191 | }` 192 | ); 193 | 194 | expect(res).toEqual({ 195 | data: { 196 | film: { 197 | title: 'A New Hope', 198 | producer: { 199 | name: 'Gary Kurtz, Rick McCallum', 200 | }, 201 | }, 202 | }, 203 | }); 204 | }); 205 | 206 | it('check array of swallow objects', async () => { 207 | const restApiResponse = { 208 | name: 'Luke Skywalker', 209 | limbs: [ 210 | { kind: 'arm', position: 'left', length: 76 }, 211 | { kind: 'arm', position: 'right', length: 76, ring: true }, 212 | { kind: 'leg', position: 'left', length: 81, sock: 'red' }, 213 | { kind: 'leg', position: 'right', length: 82, sock: 'red' }, 214 | ], 215 | }; 216 | 217 | const PersonTC = composeWithJson('PersonCustom', restApiResponse); 218 | expect(PersonTC.getFieldOTC('limbs').getFieldTypeName('ring')).toEqual('Boolean'); 219 | expect(PersonTC.getFieldOTC('limbs').getFieldTypeName('sock')).toEqual('String'); 220 | 221 | const schema1 = new GraphQLSchema({ 222 | query: new GraphQLObjectType({ 223 | name: 'Query', 224 | fields: { 225 | person: { 226 | type: PersonTC.getType(), 227 | resolve: () => { 228 | return restApiResponse; 229 | }, 230 | }, 231 | }, 232 | }), 233 | }); 234 | 235 | const res = await graphql.graphql( 236 | schema1, 237 | `{ 238 | person { 239 | name 240 | limbs { 241 | length 242 | ring 243 | } 244 | } 245 | }` 246 | ); 247 | 248 | expect(res).toEqual({ 249 | data: { 250 | person: { 251 | name: 'Luke Skywalker', 252 | limbs: [ 253 | { length: 76, ring: null }, 254 | { length: 76, ring: true }, 255 | { length: 81, ring: null }, 256 | { length: 82, ring: null }, 257 | ], 258 | }, 259 | }, 260 | }); 261 | }); 262 | }); 263 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # graphql-compose-json 2 | 3 | [![travis build](https://img.shields.io/travis/graphql-compose/graphql-compose-json.svg)](https://travis-ci.org/graphql-compose/graphql-compose-json) 4 | [![codecov coverage](https://img.shields.io/codecov/c/github/graphql-compose/graphql-compose-json.svg)](https://codecov.io/github/graphql-compose/graphql-compose-json) 5 | [![npm](https://img.shields.io/npm/v/graphql-compose-json.svg)](https://www.npmjs.com/package/graphql-compose-json) 6 | [![trends](https://img.shields.io/npm/dt/graphql-compose-json.svg)](http://www.npmtrends.com/graphql-compose-json) 7 | [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/) 8 | 9 | This is a plugin for [graphql-compose](https://github.com/nodkz/graphql-compose), which generates GraphQLTypes from REST response or any JSON. It takes fields from object, determines their types and construct GraphQLObjectType with same shape. 10 | 11 | ## Demo 12 | 13 | We have a [Live demo](https://graphql-compose-swapi.herokuapp.com/?query=%7B%0A%20%20person%28id%3A%201%29%20%7B%0A%20%20%20%20name%0A%20%20%20%20films%20%7B%0A%20%20%20%20%20%20title%0A%20%20%20%20%20%20release_date%0A%20%20%20%20%20%20director%0A%20%20%20%20%7D%0A%20%20%20%20homeworld%20%7B%0A%20%20%20%20%20%20name%0A%20%20%20%20%20%20climate%0A%20%20%20%20%20%20diameter%0A%20%20%20%20%7D%0A%20%20%20%20starships%20%7B%0A%20%20%20%20%20%20name%0A%20%20%20%20%20%20cost_in_credits%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D%0A) (source code [repo](https://github.com/lyskos97/graphql-compose-swapi)) which shows how to build an API upon [SWAPI](https://swapi.co) using `graphql-compose-json`. 14 | 15 | ## Installation 16 | 17 | ```bash 18 | npm install graphql graphql-compose graphql-compose-json --save 19 | ``` 20 | 21 | Modules `graphql`, `graphql-compose`, are located in `peerDependencies`, so they should be installed explicitly in your app. They have global objects and should not have ability to be installed as submodule. 22 | 23 | ## Example 24 | 25 | You have a sample response object `restApiResponse` which you can pass to `graphql-compose-json` along with desired type name as your first argument and it will automatically generate a composed GraphQL type `PersonTC`. 26 | 27 | ```js 28 | // person.js 29 | 30 | import { composeWithJson, composeInputWithJson } from 'graphql-compose-json'; 31 | 32 | const restApiResponse = { 33 | name: 'Anakin Skywalker', 34 | birth_year: '41.9BBY', 35 | gender: 'male', 36 | mass: 77, 37 | homeworld: 'https://swapi.co/api/planets/1/', 38 | films: [ 39 | 'https://swapi.co/api/films/5/', 40 | 'https://swapi.co/api/films/4/', 41 | 'https://swapi.co/api/films/6/', 42 | ], 43 | species: ['https://swapi.co/api/species/1/'], 44 | starships: [ 45 | 'https://swapi.co/api/starships/59/', 46 | 'https://swapi.co/api/starships/65/', 47 | 'https://swapi.co/api/starships/39/', 48 | ], 49 | }; 50 | 51 | export const PersonTC = composeWithJson('Person', restApiResponse); 52 | export const PersonGraphQLType = PersonTC.getType(); // GraphQLObjectType 53 | 54 | export const PersonITC = composeInputWithJson('PersonInput', restApiResponse); 55 | export const PersonGraphQLInput = PersonITC.getType(); // GraphQLInputObjectType 56 | ``` 57 | 58 | ## Customization 59 | 60 | You can write custom field configs directly to a field of your API response object via function (see `mass` and `starships_count` field): 61 | 62 | ```js 63 | import { composeWithJson } from 'graphql-compose-json'; 64 | 65 | const restApiResponse = { 66 | name: 'Anakin Skywalker', 67 | birth_year: '41.9BBY', 68 | starships: [ 69 | 'https://swapi.co/api/starships/59/', 70 | 'https://swapi.co/api/starships/65/', 71 | 'https://swapi.co/api/starships/39/', 72 | ], 73 | mass: () => 'Int!', // by default JSON numbers coerced to Float, here we set up Int 74 | starships_count: () => ({ // more granular field config with resolve function 75 | type: 'Int', 76 | resolve: source => source.starships.length, 77 | }), 78 | }; 79 | 80 | export const CustomPersonTC = composeWithJson('CustomPerson', restApiResponse); 81 | export const CustomPersonGraphQLType = CustomPersonTC.getType(); 82 | ``` 83 | 84 | Will be produced following GraphQL Type from upper shape: 85 | 86 | ```js 87 | const CustomPersonGraphQLType = new GraphQLObjectType({ 88 | name: 'CustomPerson', 89 | fields: () => { 90 | name: { 91 | type: GraphQLString, 92 | }, 93 | birth_year: { 94 | type: GraphQLString, 95 | }, 96 | starships: { 97 | type: new GraphQLList(GraphQLString), 98 | }, 99 | mass: { 100 | type: GraphQLInt, 101 | }, 102 | starships_count: { 103 | type: GraphQLInt, 104 | resolve: source => source.starships.length, 105 | }, 106 | }, 107 | }); 108 | ``` 109 | 110 | ## Schema building 111 | 112 | Now when you have your type built, you may specify the schema and data fetching method: 113 | 114 | ```js 115 | // schema.js 116 | import { GraphQLSchema, GraphQLObjectType, GraphQLNonNull, GraphQLInt } from 'graphql'; 117 | import fetch from 'node-fetch'; 118 | import { PersonTC } from './person'; 119 | 120 | const schema = new GraphQLSchema({ 121 | query: new GraphQLObjectType({ 122 | name: 'Query', 123 | fields: { 124 | person: { 125 | type: PersonTC.getType(), // get GraphQL type from PersonTC 126 | args: { 127 | id: { 128 | type: new GraphQLNonNull(GraphQLInt), 129 | } 130 | }, 131 | resolve: (_, args) => 132 | fetch(`https://swapi.co/api/people/${args.id}/`).then(r => r.json()), 133 | }, 134 | }, 135 | }), 136 | }); 137 | ``` 138 | 139 | Or do the same via `graphql-compose`: 140 | 141 | ```js 142 | import { SchemaComposer } from 'graphql-compose'; 143 | 144 | const schemaComposer = new SchemaComposer(); 145 | const PersonTC = composeWithJson('CustomPerson', restApiResponse, { schemaComposer }); 146 | 147 | schemaComposer.Query.addFields({ 148 | person: { 149 | type: PersonTC, 150 | args: { 151 | id: `Int!`, // equals to `new GraphQLNonNull(GraphQLInt)` 152 | }, 153 | resolve: (_, args) => 154 | fetch(`https://swapi.co/api/people/${args.id}/`).then(r => r.json()), 155 | }, 156 | } 157 | 158 | const schema = schemaComposer.buildSchema(); // returns GraphQLSchema 159 | ``` 160 | 161 | ## Building schema asynchronously 162 | 163 | To build the schema at the runtime, you should rewrite the `Schema.js` and insert there an async function which will return a promise: 164 | 165 | ```js 166 | export const buildAsyncSchema = async (): Promise => { 167 | const url = `https://swapi.co/api/people/1`; 168 | const data = await fetch(url); 169 | const jsonData = await data.json(); 170 | 171 | const PeopleTC = composeWithJson('People', jsonData); 172 | 173 | schemaComposer.Query.addFields({ 174 | person: { 175 | type: PeopleTC, 176 | args: { 177 | id: 'Int!', 178 | }, 179 | resolve: (_, args) => { 180 | return fetch(`https://swapi.co/api/people/${args.id}/`).then(r => r.json()); 181 | }, 182 | }, 183 | }); 184 | 185 | const schema = schemaComposer.buildSchema(); 186 | return schema; 187 | }; 188 | ``` 189 | 190 | So, you can just import this function and tell to the `express-graphql` that we are passing a promise: 191 | 192 | ```js 193 | import express from 'express'; 194 | import graphqlHTTP from 'express-graphql'; 195 | import { buildAsyncSchema } from './Schema'; 196 | 197 | const PORT = 4000; 198 | const app = express(); 199 | const promiseSchema = buildAsyncSchema(); 200 | 201 | app.use( 202 | '/graphql', 203 | graphqlHTTP(async req => ({ 204 | schema: await promiseSchema, 205 | graphiql: true, 206 | context: req, 207 | })) 208 | ); 209 | ``` 210 | 211 | ## Further customization with `graphql-compose` 212 | 213 | Moreover, `graphql-compose` allows you to pass pre-defined resolvers of other types to the response object and customize them: 214 | 215 | ```js 216 | const restApiResponse = { 217 | name: 'Anakin Skywalker', 218 | starships: () => 219 | StarshipTC.getResolver('findByUrlList') // get some standard resolver 220 | .wrapResolve(next => rp => { // wrap with additional logic 221 | const starshipsUrls = rp.source.starships; 222 | rp.args.urls = starshipsUrls; // populate `urls` arg from source 223 | return next(rp); // call standard resolver 224 | }) 225 | .removeArg('urls'), // remove `urls` args from resolver and schema 226 | }; 227 | } 228 | 229 | const PersonTC = composeWithJson('Person', restApiResponse); 230 | ``` 231 | 232 | In case you need to separate custom field definition from your response object there are `graphql-compose` methods made for this purpose. 233 | 234 | If you want to specify new fields of your type, simply use the `addFields` method of `graphql-compose`: 235 | 236 | ```js 237 | PersonTC.addFields({ 238 | vehicles_count: { 239 | type: 'Int!', // equals to `new GraphQLNonNull(GraphQLInt)` 240 | resolve: (source) => source.vehicles.length, 241 | }, 242 | }); 243 | ``` 244 | 245 | When you want to create a relation with another type simply use `addRelation` method of `graphql-compose`: 246 | 247 | ```js 248 | PersonTC.addRelation('filmObjects', { 249 | resolver: () => FilmTC.getResolver('findByUrlList'), 250 | prepareArgs: { 251 | urls: source => source.films, 252 | }, 253 | }); 254 | ``` 255 | 256 | `graphql-compose` provides a vast variety of methods for `fields` and `resolvers` (aka field configs in vanilla `GraphQL`) management of `GraphQL` types. To learn more visit [graphql-compose repo](https://github.com/nodkz/graphql-compose). 257 | 258 | ## License 259 | 260 | [MIT](https://github.com/graphql-compose/graphql-compose-json/blob/master/LICENSE.md) 261 | --------------------------------------------------------------------------------