blob: 7bd4a7e290e8884224acbbb3213eb3982ba53924 [file] [log] [blame]
/********************************************************************************
* 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, switchMap} from "rxjs/operators";
import {StatementsApiService} from "../../../core/api/statements/statements-api.service";
import {arrayToEntities} from "../../../util/store.util";
import {fetchStatementDetailsAction, fetchStatementsAction, setStatementEntitiesAction} from "../statements.actions";
@Injectable({providedIn: "root"})
export class FetchStatementsEffect {
public readonly fetch$ = createEffect(() => this.actions.pipe(
ofType(fetchStatementsAction),
switchMap(() => this.fetchStatements())
));
public readonly fetchDetails$ = 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) => {
const entities = arrayToEntities(statements, (statement) => statement.id);
return setStatementEntitiesAction({entities});
}),
retry(2),
catchError(() => EMPTY)
);
}
public fetchStatementDetails(id: number): Observable<Action> {
return this.statementsApiService.getStatement(id).pipe(
map((statement) => [statement]),
map((statements) => {
const entities = arrayToEntities(statements, (statement) => statement.id);
return setStatementEntitiesAction({entities});
}),
retry(2),
catchError(() => EMPTY)
);
}
}