All files / src/app/core/pipes feature-toggle.pipe.ts

100% Statements 13/13
77.77% Branches 7/9
100% Functions 3/3
100% Lines 12/12

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 413x 3x     3x                       3x   40x     40x     60x   20x     60x       80x 80x     60x      
import { ChangeDetectorRef, DestroyRef, Pipe, PipeTransform, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subscription } from 'rxjs';
 
import { FeatureToggleService, FeatureToggleType } from 'ish-core/feature-toggle.module';
 
/**
 * Pipe
 *
 * Used on a string, this pipe will only return true if the specified feature *is enabled*.
 * For the corresponding directive, see {@link FeatureToggleDirective}.
 *
 * @example
 * <ish-product-add-to-compare *ngIf="'compare' | ishFeature"> ...</ish-product-add-to-compare>
 */
@Pipe({ name: 'ishFeature', pure: false })
export class FeatureTogglePipe implements PipeTransform {
  private enabled: boolean;
  private destroyRef = inject(DestroyRef);
  private subscription: Subscription;
 
  constructor(private featureToggleService: FeatureToggleService, private cdRef: ChangeDetectorRef) {}
 
  transform(feature: 'always' | 'never' | FeatureToggleType): boolean {
    if (this.subscription) {
      // eslint-disable-next-line ban/ban
      this.subscription.unsubscribe();
    }
 
    this.subscription = this.featureToggleService
      .enabled$(feature)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(val => {
        this.enabled = val;
        this.cdRef.markForCheck();
      });
 
    return this.enabled;
  }
}