blob: d9a77a6178e39c1fcb914561b58491a0f5d43ecd [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 {asyncScheduler, Observable} from "rxjs";
import {concatMap, endWith, filter, map, startWith, throttleTime} from "rxjs/operators";
import {ContactsApiService, IAPISearchOptions} from "../../../../core";
import {catchErrorTo, catchHttpErrorTo, EHttpStatusCodes} from "../../../../util";
import {setErrorAction} from "../../../root/actions";
import {EErrorCode} from "../../../root/model";
import {setContactsLoadingState, setContactsSearchAction, startContactSearchAction} from "../../actions";
@Injectable({providedIn: "root"})
export class SearchContactsEffectService {
public search$ = createEffect(() => this.actions.pipe(
ofType(startContactSearchAction),
filter((action) => action.options != null),
throttleTime(200, asyncScheduler, {leading: true, trailing: true}),
concatMap((action) => this.search(action.options))
));
public constructor(public actions: Actions, public contactsApiService: ContactsApiService) {
}
public search(options: IAPISearchOptions): Observable<Action> {
return this.contactsApiService.getContacts(options).pipe(
map((results) => setContactsSearchAction({results})),
catchHttpErrorTo(setErrorAction({error: EErrorCode.CONTACT_MODULE_NO_ACCESS}), EHttpStatusCodes.FORBIDDEN),
catchErrorTo(setErrorAction({error: EErrorCode.UNEXPECTED})),
startWith(setContactsLoadingState({state: {searching: true}})),
endWith(setContactsLoadingState({state: {searching: false}}))
);
}
}