blob: 3d1c51daa7c502cf10bafc8f4b3996575987c73c [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 {Observable} from "rxjs";
import {filter, ignoreElements, map, retry, switchMap} from "rxjs/operators";
import {StatementsApiService} from "../../../../core/api/statements";
import {catchErrorTo, endWithObservable} from "../../../../util/rxjs";
import {setErrorAction} from "../../../root/actions";
import {EErrorCode} from "../../../root/model";
import {addCommentAction, deleteCommentAction, fetchCommentsAction, updateStatementEntityAction} from "../../actions";
@Injectable({providedIn: "root"})
export class CommentsEffect {
public fetch$ = createEffect(() => this.actions.pipe(
ofType(fetchCommentsAction),
filter((action) => action.statementId != null),
switchMap((action) => this.fetchComments(action.statementId))
));
public add$ = createEffect(() => this.actions.pipe(
ofType(addCommentAction),
filter((action) => action.statementId != null && action.text != null),
switchMap((action) => this.addComment(action.statementId, action.text))
));
public delete$ = createEffect(() => this.actions.pipe(
ofType(deleteCommentAction),
filter((action) => action.statementId != null && action.commentId != null),
switchMap((action) => this.deleteComment(action.statementId, action.commentId))
));
public constructor(public actions: Actions, private readonly statementsApiService: StatementsApiService) {
}
public fetchComments(statementId: number): Observable<Action> {
return this.statementsApiService.getComments(statementId).pipe(
map((comments) => updateStatementEntityAction({statementId, entity: {comments}})),
retry(2),
catchErrorTo(setErrorAction({error: EErrorCode.UNEXPECTED})),
);
}
public addComment(statementId: number, comment: string): Observable<Action> {
return this.statementsApiService.putComment(statementId, comment).pipe(
ignoreElements(),
retry(2),
catchErrorTo(setErrorAction({error: EErrorCode.UNEXPECTED})),
endWithObservable(() => this.fetchComments(statementId))
);
}
public deleteComment(statementId: number, commentId: number): Observable<Action> {
return this.statementsApiService.deleteComment(statementId, commentId).pipe(
ignoreElements(),
retry(2),
catchErrorTo(setErrorAction({error: EErrorCode.UNEXPECTED})),
endWithObservable(() => this.fetchComments(statementId))
);
}
}