Last active
December 14, 2023 21:53
-
-
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.
This file contains 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
'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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: