All files / app/store profile.ts

53.57% Statements 15/28
45.45% Branches 5/11
25% Functions 2/8
55% Lines 11/20

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  1x                     1x   1x 1x 1x         1x   1x       1x       2x 2x 2x                                          
import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { isEqual, omit } from 'lodash-es';
import { makeAutoObservable, observable, runInAction } from 'mobx';
import { catchError, EMPTY, Subscription } from 'rxjs';
import { Page } from '../model/page';
import { Profile, ProfilePageArgs } from '../model/profile';
import { ProfileService } from '../service/api/profile.service';
 
@Injectable({
  providedIn: 'root'
})
export class ProfileStore {
 
  args?: ProfilePageArgs = {} as any;
  page?: Page<Profile> = {} as any;
  error?: HttpErrorResponse = {} as any;
 
  private running?: Subscription;
 
  constructor(
    private profiles: ProfileService,
  ) {
    makeAutoObservable(this, {
      args: observable.struct,
      page: observable.ref,
    });
    this.clear(); // Initial observables may not be null for MobX
  }
 
  clear() {
    this.args = undefined;
    this.page = undefined;
    this.error = undefined;
  }
 
  setArgs(args: ProfilePageArgs) {
    if (!isEqual(omit(this.args, 'search'), omit(args, 'search'))) this.clear();
    this.args = args;
    this.refresh();
  }
 
  refresh() {
    if (!this.args) return;
    this.running?.unsubscribe();
    this.running = this.profiles.page(this.args).pipe(
      catchError((err: HttpErrorResponse) => {
        runInAction(() => this.error = err);
        return EMPTY;
      }),
    ).subscribe(p => runInAction(() => this.page = p));
  }
 
}