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]; | |
} |
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
Thank you so much for sharing this codemod. 👍 It helped me to start with jscodeshift (never used it before) and migrate some components.
I extended it to solve a few more issues specific for the project I'm working on:
step1
: Transform graphql tag to an object, split multiple fragments, add missing_data
suffix to the fragment name:step2
: Add missing_data
to type imports:step3
: Add missing_data
to fragment spreads:step4
: Switch to@kiwicom/relay
:The last step is highly opinionated - we're switching to our @kiwicom/relay wrapper mainly for the better Flow type safety.
Here is the changed source: