Skip to content

Instantly share code, notes, and snippets.

@hanford
Created September 29, 2021 23:43
Show Gist options
  • Select an option

  • Save hanford/12d76db1520da03bc4bacd13ad2c3ac9 to your computer and use it in GitHub Desktop.

Select an option

Save hanford/12d76db1520da03bc4bacd13ad2c3ac9 to your computer and use it in GitHub Desktop.
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