import { Injectable, Inject } from '@angular/core'; import { Router } from '@angular/router'; import { Actions, ofType, createEffect } from '@ngrx/effects'; import { of } from 'rxjs'; import { catchError, exhaustMap, map, tap, switchMap, take } from 'rxjs/operators'; import { PiService, Login2Response, ResponseStatus } from '@ucap-webmessenger/pi'; import { login, loginSuccess, loginFailure, loginRedirect, logout } from './actions'; import { LoginInfo } from '../../../types'; import { AuthenticationService } from '../../../services/authentication.service'; import { NativeService, UCAP_NATIVE_SERVICE } from '@ucap-webmessenger/native'; @Injectable() export class Effects { login$ = createEffect(() => this.actions$.pipe( ofType(login), map(action => action), exhaustMap((params: { loginInfo: LoginInfo; rememberMe: boolean }) => this.piService .login2({ loginId: params.loginInfo.loginId, loginPw: params.loginInfo.loginPw, companyCode: params.loginInfo.companyCode }) .pipe( map((res: Login2Response) => { if (res.status === ResponseStatus.Fail) { return loginFailure({ error: 'Failed' }); } else { return loginSuccess({ loginInfo: params.loginInfo, rememberMe: params.rememberMe, login2Response: res }); } }), catchError(error => of(loginFailure({ error }))) ) ) ) ); loginSuccess$ = createEffect( () => this.actions$.pipe( ofType(loginSuccess), tap(params => { this.nativeService .checkForUpdates() .pipe( take(1), map((update: boolean) => { if (!update) { this.authentication.login( params.loginInfo, params.rememberMe ); this.router.navigate(['/messenger']); } }), catchError(error => of(error)) ) .subscribe(); }) ), { dispatch: false } ); loginRedirect$ = createEffect( () => this.actions$.pipe( ofType(loginRedirect, logout), tap(authed => { this.router.navigate(['/account/login']); }) ), { dispatch: false } ); constructor( private actions$: Actions, private piService: PiService, private authentication: AuthenticationService, @Inject(UCAP_NATIVE_SERVICE) private nativeService: NativeService, private router: Router ) {} }