All files / src/app/shared/services summary.service.ts

100% Statements 42/42
81.82% Branches 18/22
100% Functions 12/12
100% Lines 36/36

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86101x 101x 101x   101x 101x             101x   359x     359x       359x 359x     360x 360x   360x 360x 2435x 2435x           2809x 2809x 2809x 36x               101x 5x             101x 452x               101x 51x 51x 2x     49x 48x 70x   48x 47x     1x     49x   101x  
import { HttpClient } from '@angular/common/http';
import { Injectable, NgZone } from '@angular/core';
import { Router } from '@angular/router';
 
import * as _ from 'lodash';
import { BehaviorSubject, Subscription } from 'rxjs';
 
import { ExecutingTask } from '../models/executing-task';
 
@Injectable({
  providedIn: 'root'
})
export class SummaryService {
  // Observable sources
  private summaryDataSource = new BehaviorSubject(null);
 
  // Observable streams
  summaryData$ = this.summaryDataSource.asObservable();
 
  polling: number;
 
  constructor(private http: HttpClient, private router: Router, private ngZone: NgZone) {
    this.enablePolling();
  }
 
  enablePolling() {
    this.refresh();
 
    this.ngZone.runOutsideAngular(() => {
      this.polling = window.setInterval(() => {
        this.ngZone.run(() => {
          this.refresh();
        });
      }, 5000);
    });
  }
 
  refresh() {
    Eif (this.router.url !== '/login') {
      this.http.get('api/summary').subscribe((data) => {
        this.summaryDataSource.next(data);
      });
    }
  }
 
  /**
   * Returns the current value of summaryData
   */
  getCurrentSummary(): { [key: string]: any; executing_tasks: object[] } {
    return this.summaryDataSource.getValue();
  }
 
  /**
   * Subscribes to the summaryData,
   * which is updated once every 5 seconds or when a new task is created.
   */
  subscribe(next: (summary: any) => void, error?: (error: any) => void): Subscription {
    return this.summaryData$.subscribe(next, error);
  }
 
  /**
   * Inserts a newly created task to the local list of executing tasks.
   * After that, it will automatically push that new information
   * to all subscribers.
   */
  addRunningTask(task: ExecutingTask) {
    const current = this.summaryDataSource.getValue();
    if (!current) {
      return;
    }
 
    if (_.isArray(current.executing_tasks)) {
      const exists = current.executing_tasks.find((element) => {
        return element.name === task.name && _.isEqual(element.metadata, task.metadata);
      });
      if (!exists) {
        current.executing_tasks.push(task);
      }
    } else {
      current.executing_tasks = [task];
    }
 
    this.summaryDataSource.next(current);
  }
}