Skip to content

Instantly share code, notes, and snippets.

@osamaishtiaq
Created August 24, 2023 09:46
Show Gist options
  • Save osamaishtiaq/4b7eb1a1b654a40dced6161bc866f169 to your computer and use it in GitHub Desktop.
Save osamaishtiaq/4b7eb1a1b654a40dced6161bc866f169 to your computer and use it in GitHub Desktop.
Given a graphql type, it will clean out all the comments and sort the fields alphabetically. Saves time when for example you have to compare two types.
function cleanAndSortGraphQLType(typeString) {
const lines = typeString.split('\n');
const indent = lines[1].match(/^\s*/)[0]; // Get the leading indentation
const cleanLines = lines
.map(line => line.replace(/\/\/.*/g, '').trim()) // Remove comments
.filter(line => line.length > 0); // Remove empty lines
const fields = cleanLines
.filter(line => line.includes(':'))
.sort();
const sortedType = [
cleanLines[0], // First line
...fields.map(field => `${indent}${field}`), // Preserve indentation
`${indent}}`
].join('\n');
return sortedType;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment