blob: 3a48216dcfc82d9c9b05d6c5d2b345f148fd140a [file]
/********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
import {Injectable} from "@angular/core";
import {Actions, createEffect, ofType} from "@ngrx/effects";
import {Action} from "@ngrx/store";
import {EMPTY, Observable} from "rxjs";
import {catchError, filter, map, retry, startWith, switchMap} from "rxjs/operators";
import {StatementsApiService} from "../../../core";
import {addAttachmentsAction, addStatementsAction, fetchStatementDetailsAction, fetchStatementsAction} from "../actions";
@Injectable({providedIn: "root"})
export class FetchStatementsEffect {
public readonly fetchStatements$ = createEffect(() => this.actions.pipe(
ofType(fetchStatementsAction),
switchMap(() => this.fetchStatements())
));
public readonly fetchStatementDetails$ = createEffect(() => this.actions.pipe(
ofType(fetchStatementDetailsAction),
filter((action) => typeof action?.id === "number"),
switchMap((action) => this.fetchStatementDetails(action.id))
));
public constructor(
private readonly actions: Actions,
private readonly statementsApiService: StatementsApiService
) {
}
public fetchStatements(): Observable<Action> {
return this.statementsApiService.getStatements().pipe(
map((statements) => {
return addStatementsAction({statements});
}),
retry(2),
catchError(() => EMPTY)
);
}
public fetchStatementDetails(id: number): Observable<Action> {
return this.statementsApiService.getStatement(id).pipe(
switchMap((statement) => {
return this.fetchAttachments(statement.id).pipe(
startWith(addStatementsAction({statements: [statement]}))
);
}),
retry(2),
catchError(() => EMPTY)
);
}
public fetchAttachments(statementId: number) {
return this.statementsApiService.getAllAttachments(statementId).pipe(
map((attachments) => {
return addAttachmentsAction({statementId, attachments});
}),
retry(2),
catchError(() => EMPTY)
);
}
}