doyensec / GQLSpection

GQLSpection - parses GraphQL introspection schema and generates possible queries
Apache License 2.0
66 stars 7 forks source link

Replace schema parser with graphql-core-legacy #30

Open execveat opened 1 year ago

execveat commented 1 year ago

Use https://github.com/graphql-python/graphql-core-legacy for parsing GraphQL schema and make the GraphQL-Core AST format as the main internal representation.

This should ease the maintenance and provide many features like SDL / JSON interoperability for free.

Parsing JSON schema and converting it into SDL:

from graphql.utils.build_client_schema import build_client_schema
from graphql import print_schema

with open('introspection.json') as f:
  json_schema = json.load(f)

# Parses schema from JSON representation, expectes '__schema'
schema_from_json = build_client_schema(json_schema['data'])

# Iterate over queries
for query_name in schema_from_json.get_type('Query').fields:
  print(query_name)

# Write SDL 
 with open('schema.graphql', 'w') as f:
  f.write(schema_printer.print_schema(schema))

Parsing SDL schema and converting it into JSON:

from graphql import build_ast_schema
from graphql.language.base import parse
from graphql.utils.introspection_query import introspection_query

with open('schema.graphql') as f:
  sdl_string = f.read()

schema_from_sdl = build_ast_schema(parse(sdl_string))

# Iterate over queries
for query_name in schema_from_sdl.get_type('Query').fields:
  print(query_name)

# Write JSON
with open('schema.graphql', 'w') as f:
  introspection_result = graphql.graphql(schema_from_sdl, request_string=introspection_query)
  json.dump(introspection_result, f)