Skip to content

Instantly share code, notes, and snippets.

@kassens
Last active December 14, 2023 21:53
Show Gist options
  • Save kassens/3e2ef9af1e5e1128f8fba3362bb92f98 to your computer and use it in GitHub Desktop.
Save kassens/3e2ef9af1e5e1128f8fba3362bb92f98 to your computer and use it in GitHub Desktop.
Updates graphql tags that are not within an object literal and not standalone expressions to be wrapped in an object similar to what the Relay babel plugin used to do before simplifying the logic there.
'use strict';
// To be used with jscodeshift: https://github.com/facebook/jscodeshift
export default function transformer(file, api) {
const j = api.jscodeshift;
if (!file.source.includes('graphql`')) {
return;
}
source = j(source)
.find(j.TaggedTemplateExpression, {
tag: {type: 'Identifier', name: 'graphql'},
})
.filter(path => getAssignedObjectPropertyName(path) == null)
.filter(path => path.parentPath.node.type !== 'ExpressionStatement')
.forEach(path => {
const text = path.node.quasi.quasis[0].value.raw;
const fragmentNameMatch = text
.replace(/#.*/g, '')
.match(/fragment (\w+)/);
if (!fragmentNameMatch) {
return;
}
const fragmentName = fragmentNameMatch[1];
const [, propName] = getFragmentNameParts(fragmentName);
j(path).replaceWith(
j.objectExpression([
j.objectProperty(j.identifier(propName), path.node),
]),
);
})
.toSource();
return source;
}
function getAssignedObjectPropertyName(path) {
var property = path;
while (property) {
if (property.node.type === 'Property' && property.node.key.name) {
return property.node.key.name;
}
property = property.parentPath;
}
}
function getFragmentNameParts(fragmentName) {
const match = fragmentName.match(
/^([a-zA-Z][a-zA-Z0-9]*)(?:_([a-zA-Z][_a-zA-Z0-9]*))?$/,
);
if (!match) {
throw new Error(
'BabelPluginGraphQL: Fragments should be named ' +
'`ModuleName_fragmentName`, got `' +
fragmentName +
'`.',
);
}
const module = match[1];
const propName = match[2] || '@nocommit';
return [module, propName];
}
@hannanstd
Copy link

hannanstd commented Dec 14, 2023

Thank you a lot but The codemod is not useful when we have multiple fragments inside one graphql tag.
I have modified it to support this situation:

// To be used with jscodeshift: https://github.com/facebook/jscodeshift

export default function transformer(file, api) {
    const j = api.jscodeshift;

    if (!file.source.includes('graphql`')) {
      return;
    }

    function getAssignedObjectPropertyName(path) {
        var property = path;
        while (property) {
            if (property.node.type === 'Property' && property.node.key.name) {
                return property.node.key.name;
            }
            property = property.parentPath;
        }
    }

    function getFragmentNameParts(fragmentName) {
        const match = fragmentName.match(
            /^([a-zA-Z][a-zA-Z0-9]*)(?:_([a-zA-Z][_a-zA-Z0-9]*))?$/,
        );
        if (!match) {
            throw new Error(
                'BabelPluginGraphQL: Fragments should be named ' +
                '`ModuleName_fragmentName`, got `' +
                fragmentName +
                '`.',
            );
        }
        const module = match[1];
        const propName = match[2] || "data";
        return [module, propName];
    }

    return j(file.source)
    .find(j.TaggedTemplateExpression, { tag: { type: 'Identifier', name: 'graphql' } })
    .filter(path => getAssignedObjectPropertyName(path) == null)
    .filter(path => path.parentPath.node.type !== 'ExpressionStatement')
    .forEach(path => {
        const text = path.node.quasi.quasis[0].value.raw;
        if (!text.includes('fragment ')) {
          return;
        }

        const fragmentStrings = text.replace(/#.*/g, '')
          .split('fragment ')
          .map(item => item.trim())
          .filter(item => item !== '' && !item.startsWith('query') && !item.startsWith('mutation'))
          .map(item => `fragment ${item}`);

        const expressions = fragmentStrings.map((fragmentString) => {
          const fragmentNameMatch =  fragmentString.match(/fragment\s+(\w+)/);
          if (!fragmentNameMatch) {
            return;
          }

          const fragmentName = fragmentNameMatch[1];
          const [, propName] = getFragmentNameParts(fragmentName);

          const key = j.identifier(propName);
          const value = j.taggedTemplateExpression(
              j.identifier('graphql'),
              j.templateLiteral([
                j.templateElement({ cooked: fragmentString, raw: fragmentString }, true ),
              ], []),
            );

          return j.objectProperty(key, value);
        }).filter(Boolean)

        if (expressions.length > 0) {
          j(path).replaceWith(j.objectExpression(expressions));
        }
    })
    .toSource();
}

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