Last active
January 27, 2021 07:41
-
-
Save iegik/57661fcecf88aa61a8c78162a4f56335 to your computer and use it in GitHub Desktop.
Generates schema of GraphQL for http://example.com/graphql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fetch from 'node-fetch'; | |
import jsonfile from 'jsonfile'; | |
const GQL = (query, variables) => ({query, variables}) | |
const request = (...args) => { | |
try { | |
return fetch(...args) | |
} catch (e) { | |
return Promise.reject({errors:[e]}); | |
} | |
}; | |
const {assign} = Object; | |
const API = (url, options) => body => request(url, assign({}, options, {body})); | |
const graphqlAPI = body => (new API('http://example.com/graphql', { | |
method: 'POST', | |
headers: {'Content-Type': 'application/json'}, | |
}))(JSON.stringify(GQL(body))).then(res => res.json()); | |
const getTypeInfo = type => graphqlAPI(`{ | |
__type(name: "${type.name}") { | |
name | |
description | |
fields { | |
name | |
type { | |
name | |
kind | |
} | |
} | |
} | |
}`); | |
const saveAs = (filename, obj) => jsonfile.writeFile(filename, obj, err => console.log(err)); | |
const save = (obj) => saveAs(__dirname + '/schema.json', obj); | |
graphqlAPI(`{ | |
__schema { | |
types { | |
name | |
kind | |
ofType { | |
name | |
kind | |
} | |
} | |
directives { | |
name | |
description | |
locations | |
args | |
} | |
} | |
}`).then(({data}) => | |
Promise.all(data.__schema.types.map(getTypeInfo)) | |
.then(types => types.map(({data:{__type}}) => __type)) | |
.then(types => ({data: {__schema: {types, directives: data.__schema.directives}}})) | |
.then(save) | |
//.then(data => {console.log(JSON.stringify(data))}) | |
.catch(e => console.error(e)) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment