All files / src/app/core/utils/feature-toggle feature-toggle.service.ts

100% Statements 17/17
88.88% Branches 8/9
100% Functions 5/5
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53195x 195x 195x 195x     195x       195x       301x 48x 253x 48x   205x         195x 42x     42x                     7x             5x 5x          
import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { BehaviorSubject, Observable } from 'rxjs';
import { distinctUntilChanged, map } from 'rxjs/operators';
import type { Environment } from 'src/environments/environment.model';
 
import { getFeatures } from 'ish-core/store/core/configuration';
 
export type FeatureToggleType = Environment['features'][number];
 
export function checkFeature(
  features: FeatureToggleType[] = [],
  feature: 'always' | 'never' | FeatureToggleType
): boolean {
  if (feature === 'always') {
    return true;
  } else if (feature === 'never') {
    return false;
  } else {
    return features.includes(feature);
  }
}
 
@Injectable({ providedIn: 'root' })
export class FeatureToggleService {
  private featureToggles$ = new BehaviorSubject<FeatureToggleType[]>(undefined);
 
  constructor(store: Store) {
    store.pipe(select(getFeatures)).subscribe(this.featureToggles$);
  }
 
  /**
   * Synchronously check if {@param feature} is active.
   *
   * This method should only be used for browser code and only for
   * logic that is not included in the initialization process.
   */
  enabled(feature: 'always' | 'never' | FeatureToggleType): boolean {
    // eslint-disable-next-line rxjs/no-subject-value
    return checkFeature(this.featureToggles$.value, feature);
  }
 
  /**
   * Asynchronously check if {@param feature} is active.
   */
  enabled$(feature: 'always' | 'never' | FeatureToggleType): Observable<boolean> {
    return this.featureToggles$.pipe(
      map(featureToggles => checkFeature(featureToggles, feature)),
      distinctUntilChanged()
    );
  }
}