import { Injectable } from '@angular/core' ; import { HttpClient } from '@angular/common/http' ; import { Observable } from 'rxjs' ; import { catchError , finalize , map } from 'rxjs/operators' ; import { Session } from './session.model' ; import { CONFIG , ExceptionService , MessageService , SpinnerService } from '../../core' ; const sessionsUrl = CONFIG . baseUrls . sessions ; @ Injectable ( { providedIn : 'root' } ) export class SessionService { onDbReset = this . messageService . state ; private catchHttpErrors = ( ) => ( source$ ) => source$ . pipe ( catchError ( this . exceptionService . catchBadResponse ) , finalize ( ( ) => this . spinnerService . hide ( ) ) ) ; constructor ( private http , private exceptionService , private messageService , private spinnerService ) { this . messageService . state . subscribe ( state => this . getSessions ( ) ) ; } addSession ( session ) { this . spinnerService . show ( ) ; return this . http . post < Session > ( `${ sessionsUrl }` , session ) . pipe ( this . catchHttpErrors ( ) ) ; } deleteSession ( session ) { this . spinnerService . show ( ) ; return < Observable < Session > > ( this . http . delete ( `${ sessionsUrl }/${ session . id }` ) . pipe ( this . catchHttpErrors ( ) ) ) ; } getSessions ( ) { this . spinnerService . show ( ) ; return this . http . get < Session [ ] > ( sessionsUrl ) . pipe ( map ( sessions => this . sortSessions ( sessions ) ) , this . catchHttpErrors ( ) ) ; } sortSessions ( sessions ) { return sessions . sort ( ( a , b ) => { if ( a . name < b . name ) { return - 1 ; } if ( a . name > b . name ) { return 1 ; } return 0 ; } ) ; } getSession ( id ) { this . spinnerService . show ( ) ; return this . http . get < Session > ( `${ sessionsUrl }/${ id }` ) . pipe ( this . catchHttpErrors ( ) ) ; } updateSession ( session ) { this . spinnerService . show ( ) ; return this . http . put < Session > ( `${ sessionsUrl }/${ session . id }` , session ) . pipe ( this . catchHttpErrors ( ) ) ; } }