import { DocumentNode , Kind , ObjectTypeDefinitionNode , OperationTypeDefinitionNode , parse } from 'graphql' ; import { GraphQLSchema } from 'graphql/type/schema' ; import { buildASTSchema } from 'graphql/utilities/buildASTSchema' ; import { generators } from './generators' ; import { Generator } from './types' ; export { Generator } from './types' ; param schema { String } returns { String } const sanitizeSchema = ( schema ) => schema . replace ( /\`/g , '\'' ) ; export function generateCode ( schema , generator ) { if ( typeof generator === 'string' ) { generator = generators [ generator ] || require ( generator ) . generator ; if ( ! generator ) { throw new Error ( `Generator '${ generator }' could not be found. Available generators:
${ Object . keys ( generators ) . map ( k => `'${ k }` ) . join ( ', ' ) }` ) ; } } schema = sanitizeSchema ( schema ) ; const document = parse ( schema , { noLocation : true } ) ; const ast = buildASTSchema ( document ) ; const typeNames = Object . keys ( ast . getTypeMap ( ) ) . filter ( typeName => ! typeName . startsWith ( '__' ) ) . filter ( typeName => typeName !== ast . getQueryType ( ) . name ) . filter ( typeName => ast . getMutationType ( ) ? typeName !== ast . getMutationType ( ) ! . name : true ) . filter ( typeName => ast . getSubscriptionType ( ) ? typeName !== ast . getSubscriptionType ( ) ! . name : true ) . sort ( ( a , b ) => ast . getType ( a ) . constructor . name < ast . getType ( b ) . constructor . name ? - 1 : 1 ) ; const generatedClass = [ generator . Header ( schema ) ] ; generatedClass . push ( ... typeNames . map ( typeName => { const type = ast . getTypeMap ( ) [ typeName ] ; return generator [ type . constructor . name ] ? generator [ type . constructor . name ] ( type ) : null ; } ) ) ; if ( generator . SchemaType ) { generatedClass . push ( generator . SchemaType ( ast . getQueryType ( ) , ast . getMutationType ( ) , ast . getSubscriptionType ( ) ) ) ; } if ( generator . RootType ) { generatedClass . push ( generator . RootType ( ast . getQueryType ( ) ) ) ; if ( ast . getMutationType ( ) ) { generatedClass . push ( generator . RootType ( ast . getMutationType ( ) ! ) ) ; } } if ( generator . SubscriptionType ) { if ( ast . getSubscriptionType ( ) ) { generatedClass . push ( generator . SubscriptionType ( ast . getSubscriptionType ( ) ! ) ) ; } } generatedClass . push ( generator . Main ( ast . getQueryType ( ) , ast . getMutationType ( ) , ast . getSubscriptionType ( ) ) ) ; return generatedClass . filter ( r => r ) . join ( '\n\n' ) ; }