Skip to content

Instantly share code, notes, and snippets.

@hanford
Last active March 1, 2022 10:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hanford/10401629eb7d82d47b275f59356d86f5 to your computer and use it in GitHub Desktop.
Save hanford/10401629eb7d82d47b275f59356d86f5 to your computer and use it in GitHub Desktop.
/* eslint-enable no-param-reassign */
function genId() {
const num = uuid();
return `graphql__${num}`;
}
function uuid() {
return 'xxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (Math.random() * 16) | 0,
v = c == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
module.exports = function (babel) {
const { types: t } = babel;
let gqlTags = [];
function TaggedTemplateExpression({ node, parent }) {
const isGraphql = node.tag.name === 'graphql';
if (isGraphql) {
const moduleId = genId();
const contents = node.quasi.quasis[0].value.raw.trim();
const name = /(fragment|mutation|query) (\w+)/.exec(contents)[2];
const nextValue = t.identifier(moduleId);
gqlTags.push({ name, id: moduleId });
switch (parent.type) {
case 'ObjectProperty':
parent.value = nextValue;
return;
case 'VariableDeclarator':
parent.init = nextValue;
return;
case 'CallExpression':
parent.arguments[0] = nextValue;
return;
case 'JSXExpressionContainer':
parent.expression = nextValue;
return;
default:
}
}
}
return {
name: 'FF', // not required
visitor: {
Program: {
enter() {
// Reset variables when we enter a new file
gqlTags = [];
},
exit(path) {
gqlTags.forEach(({ name, id }) => {
const identifier = t.identifier(id);
const importDefaultSpecifier = t.importDefaultSpecifier(identifier);
const importDeclaration = t.importDeclaration(
[importDefaultSpecifier],
t.stringLiteral(`dazzle-types/${name}.graphql`),
);
path.unshiftContainer('body', importDeclaration);
});
},
},
TaggedTemplateExpression,
},
};
};
@hanford
Copy link
Author

hanford commented Oct 15, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment