Created
June 16, 2021 05:03
-
-
Save Quramy/9136f4a3403905eb6810b665fea8196e to your computer and use it in GitHub Desktop.
Remove unused GraphQL fragment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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