Skip to content

Instantly share code, notes, and snippets.

@Quramy
Created June 16, 2021 05:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Quramy/9136f4a3403905eb6810b665fea8196e to your computer and use it in GitHub Desktop.
Save Quramy/9136f4a3403905eb6810b665fea8196e to your computer and use it in GitHub Desktop.
Remove unused GraphQL fragment
import assert from "assert";
import { parse, print, DocumentNode, visit } from "graphql";
function removeUnusedFragment(document: DocumentNode) {
const usedFragmentSet = new Set<string>();
// mark used
visit(document, {
FragmentSpread(node) {
usedFragmentSet.add(node.name.value);
}
});
// sweep
const doc = visit(document, {
FragmentDefinition(node) {
if (usedFragmentSet.has(node.name.value)) return;
return null;
}
});
return doc;
}
const rawDocStr = `
fragment A on Hoge {
id
}
fragment B on Hoge {
id
}
fragment C on Hoge {
...A
}
query Query {
...C
}
`;
const rawDocNode = parse(rawDocStr);
const docNode = removeUnusedFragment(rawDocNode);
console.log(print(docNode));
// fragment A on Hoge {
// id
// }
//
// fragment C on Hoge {
// ...A
// }
//
// query Query {
// ...C
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment