Skip to content

Instantly share code, notes, and snippets.

@kastigar
Created November 15, 2016 08:20
Show Gist options
  • Save kastigar/68ca1218f12aafa8d5711d2eb21c28ab to your computer and use it in GitHub Desktop.
Save kastigar/68ca1218f12aafa8d5711d2eb21c28ab to your computer and use it in GitHub Desktop.
module.exports = function AutotypePlugin({ types: t }) {
const gettersByType = {
VariableDeclarator(path) {
const { id } = path.parent;
if (t.isIdentifier(id)) {
return id.name;
}
console.log(`Unsupported VariableDeclarator.id: ${id.type}`);
return null;
},
ObjectProperty(path) {
const { key, computed } = path.parent;
if (t.isStringLiteral(key)) {
return key.value;
}
if (t.isIdentifier(key)) {
return computed ? null : key.name;
}
console.log(`Unsupported ObjectPropery.key: ${key.type}`);
return null;
},
ClassProperty(path) {
const { key } = path.parent;
if (t.isIdentifier(key)) {
return key.name;
}
console.log(`Unsupported ClassProperty.key: ${key.type}`);
return null;
},
AssignmentExpression(path) {
const { left, operator } = path.parent;
if (operator !== '=') {
return null;
}
if (t.isIdentifier(left)) {
return left.name;
}
if (t.isMemberExpression(left) && t.isIdentifier(left.property)) {
return left.computed ? null : left.property.name;
}
console.log(`Unsupported AssignmentExpression.key: ${left.type}`);
return null;
},
};
return {
visitor: {
CallExpression(path) {
if (!t.isIdentifier(path.node.callee, { name: 'actionCreator' })) {
return;
}
const getActionType = gettersByType[path.parent.type];
if (!getActionType) {
console.log(`Unsupported: ${path.parent.type}`);
return;
}
const actionType = getActionType(path);
if (actionType) {
console.log(`Added: ${actionType}`);
path.node.arguments.unshift(t.stringLiteral(actionType));
}
},
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment