Skip to content

Instantly share code, notes, and snippets.

@konsumer konsumer/gen_queries.js
Last active Jun 27, 2018

Embed
What would you like to do?
Make a set of mega-queries from a running GraphQL server. This recurses infinitely, so make sure you really want all the fields it requests
/**
* Generate a complete set of queries from running GraphQL server
*/
import { getSortedTypes } from './utils'
// get your schema however you do that, here
/**
here is an example:
import { makeExecutableSchema } from 'graphql-tools'
import jsonResolver from 'graphql-type-json'
import { fileLoader, mergeTypes, mergeResolvers } from 'merge-graphql-schemas'
export const resolvers = mergeResolvers(fileLoader(`${__dirname}/resolvers/**/*.js`))
resolvers.JSON = jsonResolver
export const typeDefs = mergeTypes(fileLoader(`${__dirname}/../schema/**/*.graphql`), { all: true }) + '\n scalar JSON'
const schema = makeExecutableSchema({ typeDefs, resolvers })
export default schema
*/
import schema from '../src/index'
// get a fragments for some types
export const createFragment = type => {
if (type.kind === 'ENUM') {
return `# ENUM ${type.name}: ${type.enumValues.map(e => e.name).join(', ')}`
}
const out = []
out.push(`fragment ${type.name}Full on ${type.name} {`)
type.fields.forEach(field => {
if (field.type.ofType && field.type.ofType.kind === 'OBJECT') {
out.push(` ${field.name} { ...${field.type.ofType.name}Full }`)
} else {
if (field.type.kind === 'OBJECT') {
out.push(` ${field.name} { ...${field.type.name}Full }`)
} else {
out.push(` ${field.name}`)
}
}
})
out.push('}')
return out.join('\n')
}
// get a function-query from a field of Query
export const queryFromField = func => {
const args = func.args.length ? `( ${func.args.map(arg => `${arg.name}: $${arg.name}`).join(', ')} )` : ''
const innerargs = func.args.length ? `( ${func.args.map(arg => `$${arg.name}: ${arg.type.ofType.name}${arg.type.kind === 'NON_NULL' ? '!' : ''}`).join(', ')} ) ` : ''
const outName = func.type.ofType ? func.type.ofType.name : func.type.name
return `query ${func.name}Demo ${innerargs}{\n ${func.name}${args}{ ...${outName}Full }\n}`
}
async function run () {
const { structure, types } = await getSortedTypes(schema)
const Query = (types.filter(t => t.name === structure.__schema.queryType.name)).pop()
if (!Query) {
console.error('Could not find query-type!')
process.exit(1)
}
const functions = Query.fields
.map(queryFromField)
const fragments = types
.filter(type => type.name !== 'Query')
.map(createFragment)
console.log(`${functions.join('\n\n')}\n\n${fragments.join('\n\n')}`)
}
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.