eslint-plugin-ember icon indicating copy to clipboard operation
eslint-plugin-ember copied to clipboard

False positive for `no-unused-services` when component is passed to function expressions

Open tehhowch opened this issue 3 years ago • 2 comments

Ember 3.24 ESlint v7.31 eslint-plugin-ember v10.5.1

While evaluating this rule on apps at work, I discovered it triggered in the following scenario:

import Component from '@glimmer/component';
import { inject as service } from '@ember/service';

const SomeUtilityFn = (component) => component.someService.someMethod();

export default class MyComponent extends Component {
  @service someService;

  get foo() {
    return SomeUtilityFn(this);
  }
}

Given that the helper method is defined in this file (vs imported), I didn't expect the rule to be triggered.

tehhowch avatar Jul 23 '21 19:07 tehhowch

This is a good edge case that we could try fixing. It might be tricky to statically detect this usage of the service, although it should be possible.

I'm not sure if this is the most elegant way, but something like this:

  1. Inside the component, check for any function calls with this as an argument.
  2. For any such functions, check if they are defined in the same file.
  3. If they are, check inside their function scope to see if the relevant parameter has a service accessed off of it.

bmish avatar Jul 23 '21 20:07 bmish

The same logic would also improve the require-computed-property-dependencies rule, which fails to deduce a missing declared dependency for the same pattern:

import Component from '@ember/component';
import { computed } from '@ember/object';

const SomeUtilityFn = (component) => component.prop;

export default Component.extend({
  prop: 1,
  bar: 2,

  foo: computed('bar', function () {
    return bar && SomeUtilityFn(this);
  }), // require-computed-property-dependencies fails to warn about undeclared dependency on `prop`
});

tehhowch avatar Jul 25 '21 02:07 tehhowch