Effect

 avatar
unknown
javascript
5 years ago
1.6 kB
7
Indexable
@Injectable()
export class ListEffects {
  @Effect()
  getCompanySummaryList$ = this.dp.fetch(fromListActions.Types.GetCompanySummaryList, {
    run: () =>
      this.listApiService
        .getCompanyList()
        .pipe(
          switchMap(companyList =>
            this.getCompanySummaryList(companyList).pipe(
              map(
                companySummary => new fromListActions.GetCompanySummarySuccess(companySummary)
              )
            )
          ),
          finalize(() => {
            this.facade.getCompanySummaryListSuccess();
          })
        ),
    onError: (action: fromListActions.GetCompanySummaryList, error: HttpErrorResponse) => new fromListActions.GetCompanySummaryListFail(error)
  });

  private getCompanySummaryList(companyList: Company[]): Observable<CompanySummary> {
    return forkJoin(
      companyList
        .sort((prev, next) => (prev.id > next.id) ? 1 : -1)
        .map((company, index) =>
          this.listApiService.getIncomeList({ companyId: company.id })
            .pipe(
              map(incomeList => {
                const calculation = new Calculation(incomeList);

                return {
                  ...company,
                  averageIncome: calculation.averageIncome,
                  lastMonthIncome: 1,
                  totalIncome: calculation.totalIncome
                } as CompanySummary;
              })
            )
        )
    ).pipe(concatAll());
  }

  constructor(
    private dp: DataPersistence<ListPartialState>,
    private actions$: Actions,
    private facade: ListFacade,
    private listApiService: ListApiService
  ) {}
}
Editor is loading...