Skip to content

Instantly share code, notes, and snippets.

@AetherDevSecOps
Created April 25, 2021 05:24
Show Gist options
  • Save AetherDevSecOps/dd5c9160ff37140b8a568883847e756f to your computer and use it in GitHub Desktop.
Save AetherDevSecOps/dd5c9160ff37140b8a568883847e756f to your computer and use it in GitHub Desktop.
Pretty print GraphQL API Schema Introspection Results
function resolveType(type){
var stack = []
var current = type;
while(current != null) {
stack.push({kind:current.kind, name:current.name})
current = current.ofType;
}
var output = "";
if(stack.length == 0){
return null;
}
while(stack.length > 0) {
var token = stack.pop()
if(token.kind == "NON_NULL") {
output = "!"+output;
}
else if(token.kind == "LIST") {
output = "["+output+"]";
}
else {
output = token.name;
}
}
return output;
}
function dumpFields(objectType, objectName, inputFields){
if(!inputFields){ inputFields = [] }
return objectType + " " + objectName + "\n "+ inputFields.map(x => {
var type = resolveType(x.type);
var methodSuffix = "";
if(x.args && x.args.length > 0) {
methodSuffix = "("+x.args.map(arg => {
var defaultValue = "";
if(arg.defaultValue) {
defaultValue = "="+arg.defaultValue;
}
return arg.name+":"+resolveType(arg.type)+defaultValue;
}).join(", ")+")";
}
return {name:x.name+methodSuffix, type:type}}).sort((a,b) => a.name.localeCompare(b.name)).map(x => x.type+" "+x.name).join("\n ")
}
function prettyPrintSchema(schema) {
var target = schema;
var types = target.data.__schema.types.sort((a,b) => a.name.localeCompare(b.name)).map((type) => {
var kind = null;
if(type.kind) {
kind = type.kind[0]+type.kind.slice(1).toLocaleLowerCase();
}
if(type.kind === "ENUM") {
return dumpFields(kind, type.name, type.enumValues)
}
if(type.kind === "INPUT_OBJECT") {
return dumpFields(kind, type.name, type.inputFields)
}
if(type.kind === "INTERFACE") {
var implementedBy = type.possibleTypes.map(type => type.name).join(", ");
var suffix = "none?"
if(implementedBy.length > 0) {
suffix = implementedBy;
}
return dumpFields(kind, type.name+" implemented by "+suffix, type.fields)
}
return dumpFields(kind, type.name, type.fields)
}).join("\n\n")
var directives = target.data.__schema.directives.map((directive) => {
return dumpFields("Directive ("+directive.locations.join(", ")+")", directive.name, directive.args)
}).join("\n\n")
return directives+"\n\n"+types;
}
copy( prettyPrintSchema(fetchedSchema));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment