Does anyone have or know of a code mod or refactoring plugin for VS Code that will refactor multiple subscribe arguments into one argument object? I have many existing observables using multiple arguments, but that has been deprecated. It would be very nice if there was an automated refactor for this conversion.
See https://rxjs.dev/deprecations/subscribe-arguments
Most often people just have this format in their code.
of([1,2,3]).subscribe((success) => {...}, (err) => {...} );
which would convert to
of([1,2,3]).subscribe({ next: (success) => {...}, error: (err) => {...}} );
You can use this transformer with jscodeshift
transform_rxjs_6_to_7.js
module.exports = function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
// Find all method calls to `subscribe`
root.find(j.CallExpression, {
callee: {
property: {name: 'subscribe'}
},
arguments: args =>
args.length == 0
|| (args.length > 0 && !j.ObjectExpression.check(args[0]))
}).replaceWith(path => {
const {node} = path;
// Wrap the argument in an object with `next` property
const properties = [];
if (node.arguments.length > 0) {
properties.push(
j.property('init', j.identifier('next'), node.arguments[0]));
}
if (node.arguments.length > 1) {
properties.push(
j.property('init', j.identifier('error'), node.arguments[1]));
}
if (node.arguments.length > 2) {
properties.push(
j.property('init', j.identifier('complete'), node.arguments[2]));
}
node.arguments = [j.objectExpression(properties)];
return node;
});
return root.toSource();
};
and run it with
npx jscodeshift --parser ts --transform=transform_rxjs_6_to_7.js --extensions=js,ts src
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With