Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lnmunhoz/e9b096f6bb89ab584b9bf4164ae81caa to your computer and use it in GitHub Desktop.
Save lnmunhoz/e9b096f6bb89ab584b9bf4164ae81caa to your computer and use it in GitHub Desktop.
Fix Apollo Query components expecting the data prop to be an empty object
/**
* This transformer adds an empty object assignment to every Query component in the codebase.
* It will only touch the file if it find a Query that has object destructuring assignment.
* https://astexplorer.net/#/gist/a52e94d33bf5329027fddc77b95d9fe5/7b18cb8ae69e0ab4413375276863632cf6307d52
*/
export default function transformer(file, api) {
const j = api.jscodeshift
return j(file.source)
.find(j.JSXElement, path => path.openingElement.name.name === 'Query')
.find(j.ArrowFunctionExpression, path => {
const isObjectPattern =
path.params.length === 1 && path.params[0].type === 'ObjectPattern'
if (isObjectPattern) {
const properties = path.params[0].properties
const dataProp = properties.find(p => p.key.name === 'data')
if (dataProp) {
const isDestructuring = dataProp.value.type === 'ObjectPattern'
return isDestructuring
}
} else {
return false
}
})
.forEach(path => {
const data = path.value.params[0].properties.find(
p => p.key.name === 'data'
)
if (data.value.type === 'ObjectPattern') {
// Store previous props
const previous = Object.assign({}, data.value)
// Add with assignment pattern
data.value.type = 'AssignmentPattern'
// Add the old props to left side
data.value.left = previous
// Replace with empty object initialization
data.value.right = {
type: 'ObjectPattern',
properties: []
}
}
})
.toSource()
}
@siddharthkp
Copy link

Oh hey! thanks @lnmunhoz :)

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