Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code mod/shift to refactor rxjs subscribe method

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) => {...}} );
like image 949
Ulfius Avatar asked Aug 14 '26 05:08

Ulfius


1 Answers

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
like image 165
maiermic Avatar answered Aug 16 '26 21:08

maiermic