import { Injectable } from '@angular/core' ; import { Actions , Effect , ofType } from '@ngrx/effects' ; import { Action } from '@ngrx/store' ; import { of } from 'rxjs' ; import { map , switchMap } from 'rxjs/operators' ; import { AddTokenAction , RemoveTokenAction , } from '../auth/auth.actions' ; import { ReceivedResponseAction , RestActionTypes , SendGetRequestAction , SendPostRequestAction , } from './rest.actions' ; import { RestClient } from './rest.service' ; import { Go } from '../router/router.actions' ; @ Injectable ( ) export class RestEffects { @ Effect ( ) sendGetRequest$ = this . actions$ . pipe ( ofType ( RestActionTypes . SEND_GET_REQUEST ) , switchMap ( ( action ) => this . http . get ( action . payload . schema , action . payload . path ) . mergeMap ( ( response ) => { return [ new ReceivedResponseAction ( response ) , ] ; } ) . catch ( ( error ) => { return of ( new ReceivedResponseAction ( error ) ) ; } ) ) ) ; @ Effect ( ) sendPostRequest$ = this . actions$ . pipe ( ofType ( RestActionTypes . SEND_POST_REQUEST ) , switchMap ( ( action ) => { return this . http . post ( action . payload . schema , action . payload . path , action . payload . data ) . map ( ( response ) => { return new ReceivedResponseAction ( response ) ; } ) . catch ( ( error ) => { return of ( new ReceivedResponseAction ( error ) ) ; } ) ; } ) ) ; @ Effect ( ) processResponse$ = this . actions$ . pipe ( ofType ( RestActionTypes . RECEIVED_RESPONSE ) , map ( ( action ) => action ) , switchMap ( ( action ) : Action [ ] => { let response_url ; let response_data ; const response = action . payload ; switch ( response . status ) { case 200 : response_data = action . payload . body ; response_url = action . payload . url ; if ( response_url === 'https://api.rochard.org/rpc/login' ) { return [ new AddTokenAction ( response_data [ 0 ] . token ) ] ; } return [ ] ; case 204 : return [ ] ; case 401 : if ( response . message === 'JWT expired' ) { return [ new RemoveTokenAction ( '' ) , new Go ( { path : [ '/rpc/login' ] } ) , ] ; } else { return [ ] ; } default : return [ ] ; } } ) ) ; constructor ( private actions$ , private http ) { } }