Created
September 29, 2021 23:43
-
-
Save hanford/12d76db1520da03bc4bacd13ad2c3ac9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| export const parser = 'tsx'; | |
| // Press ctrl+space for code completion | |
| export default function transformer(file, api) { | |
| const j = api.jscodeshift; | |
| const root = j(file.source); | |
| const imports = root.find(j.ImportDeclaration); | |
| if (imports.length) { | |
| const lastImport = imports.at(imports.length - 1).get(); | |
| root.find(j.TaggedTemplateExpression, { tag: { name: 'graphql' } }).forEach(p => { | |
| const node = p.node; | |
| const contents = node.quasi.quasis[0].value.raw.trim(); | |
| const name = /(fragment|mutation|query) (\w+)/.exec(contents)[2]; | |
| const id = genId(); | |
| if (!imports.length) return; | |
| const decl = j.importDeclaration( | |
| [j.importDefaultSpecifier(j.identifier(id))], | |
| j.literal(`dazzle-types/${name}.graphql`), | |
| ); | |
| j(lastImport).insertAfter([decl]); | |
| p.replace(j.identifier(id)); | |
| }); | |
| } | |
| return root.toSource(); | |
| } | |
| function genId() { | |
| const num = uuid(); | |
| return `graphql__${num}`; | |
| } | |
| function uuid() { | |
| return 'xxxxxxxx'.replace(/[xy]/g, function idGen(c) { | |
| const r = Math.random() * 16; | |
| // eslint-disable-next-line no-bitwise | |
| const v = c === 'x' ? r : (r & 0x3) | 0x8; | |
| return v.toString(16); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment