106 lines
2.9 KiB
TypeScript
Raw Normal View History

2019-09-18 15:02:21 +09:00
import { Injectable, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { Actions, ofType, createEffect } from '@ngrx/effects';
import { of } from 'rxjs';
2019-09-19 10:40:16 +09:00
import { catchError, exhaustMap, map, tap, switchMap } from 'rxjs/operators';
2019-09-18 15:02:21 +09:00
import {
PiService,
Login2Response,
ResponseStatus
} from '@ucap-webmessenger/pi';
import {
login,
loginSuccess,
loginFailure,
loginRedirect,
2019-09-19 10:40:16 +09:00
logout,
postLoginSuccess
2019-09-18 15:02:21 +09:00
} 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) => {
console.log(res);
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 })))
)
)
)
);
2019-09-19 10:40:16 +09:00
loginSuccess$ = createEffect(() =>
this.actions$.pipe(
ofType(loginSuccess),
map(action => action),
exhaustMap(
(params: {
loginInfo: LoginInfo;
rememberMe: boolean;
login2Response: Login2Response;
}) =>
this.nativeService.checkForUpdates().pipe(
map((update: boolean) => {
2019-09-18 15:02:21 +09:00
if (!update) {
this.authentication.login(params.loginInfo, params.rememberMe);
this.router.navigate(['/messenger']);
2019-09-19 10:40:16 +09:00
return postLoginSuccess({
loginInfo: params.loginInfo,
rememberMe: params.rememberMe,
login2Response: params.login2Response
});
2019-09-18 15:02:21 +09:00
}
2019-09-19 10:40:16 +09:00
}),
catchError(error => of(error))
)
)
)
2019-09-18 15:02:21 +09:00
);
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
) {}
}