Created
December 26, 2021 02:06
-
-
Save hanford/e01b2e40e68f61c9b25e5be1869afb8a 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
| // jscodeshift can take a parser, like "babel", "babylon", "flow", "ts", or "tsx" | |
| // Read more: https://github.com/facebook/jscodeshift#parser | |
| export const parser = "tsx"; | |
| export default function transformer(file, api) { | |
| const j = api.jscodeshift; | |
| const root = j(file.source); | |
| // first collect all dazzle-type import specifiers | |
| let dazzleImportSpecifierValues = []; | |
| root.find(j.ImportDeclaration).map((i) => { | |
| const path = i.value.source.value; | |
| if (path.startsWith("dazzle-types")) { | |
| i.value.specifiers.forEach((spec) => { | |
| const value = spec.imported.name; | |
| if (!value.endsWith("$data") && !value.endsWith("$key") && !value.endsWith("$variables")) { | |
| dazzleImportSpecifierValues.push(value); | |
| } | |
| }); | |
| } | |
| }); | |
| // use $key if definitionsInFile | |
| let definitionsInFile = []; | |
| 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) (\w+)/.exec(contents)[2]; | |
| definitionsInFile.push(name); | |
| }); | |
| // iterate over all identifiers that end with one of the replacement keys | |
| const identifiers = root.find(j.Identifier); | |
| identifiers.forEach((np) => { | |
| const idName = np.value.name; | |
| if (idName.endsWith("Response")) { | |
| np.value.name = idName.replace("Response", "$data"); | |
| } | |
| if (idName.endsWith("Variables")) { | |
| np.value.name = idName.replace("Variables", "$variables"); | |
| } | |
| if (dazzleImportSpecifierValues.some((k) => k === idName)) { | |
| if (idName.includes("_")) { | |
| if (definitionsInFile.includes(idName)) { | |
| np.value.name = `${idName}$key`; | |
| } else { | |
| np.value.name = `${idName}$data`; | |
| } | |
| } | |
| } | |
| }); | |
| return root.toSource(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment