Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

codemod/transform include BlockStatement

I'm doing a codemod/transform to change if/return statements in my code.

I have a lot of if(err) do something and I need to refactor that behavior.

How can I make a transform for this?

What I have:

if (err) {
  return connection.rollback(function() {
    throw err;
  });
}

What I want:

if (err){
    return rollback(connection, err);
}

I managed so far to replace the node.consequent and use a callExpression directly:

root.find(j.IfStatement).replaceWith(function (_if) {
  var fnCall = j.callExpression(j.identifier('rollback'), [
    j.identifier('connection'), 
    j.identifier('err')
  ]);

  _if.node.consequent = fnCall; 
  return _if.node;
});

...resulting in:

if (err)
  rollback(connection, err);

How to also include the BlockStatement and a return inside it? is this the correct way to do this codemod?

live example here

like image 496
Sergio Avatar asked May 21 '26 16:05

Sergio


1 Answers

Ok, made it! What a nice tool!

please do comment or post a new answer if there is a better way to do this!

So, what i was missing was both a block statement {} in the if statement, and inside it a return.

So I added:

var ret = j.returnStatement(fnCall);
var block = j.blockStatement([ret]);
_if.node.consequent = block;

result here: http://astexplorer.net/#/84e8ZqEAwQ/1

like image 181
Sergio Avatar answered May 23 '26 05:05

Sergio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!