import { HttpClient , HttpHeaders } from '@angular/common/http' ; import { Observable , of , from as fromPromise } from 'rxjs' ; import { environment } from '@env/environment' ; import { map } from 'rxjs/operators' ; const STORAGE_ITEM = 'authToken' ; export abstract class GenericHttpService { public readonly apiEndPoint : string ; public tokentStorage = '' ; constructor ( public http ) { this . apiEndPoint = environment . apiEndpoint ; } protected get ( _path ) { const options = { headers : this . getHeaders ( ) } ; return this . http . get ( `${ this . apiEndPoint }${ _path }` , options ) . pipe ( map ( res => { if ( ( res as any ) . token ) { this . saveToken ( res ) ; } return res ; } ) ) ; } protected getFrontend ( _path ) { const options = { headers : this . getHeaders ( ) } ; return this . http . get ( `/${ _path }` , options ) . pipe ( map ( res => { return res ; } ) ) ; } protected post ( _path , body ) { const options = { headers : this . getHeaders ( ) } ; return this . http . post ( `${ this . apiEndPoint }${ _path }` , body , options ) . pipe ( map ( res => { if ( ( res as any ) . token ) { this . saveToken ( res ) ; } return res ; } ) ) ; } protected put ( _path , body ) { const url = `${ this . apiEndPoint }${ _path }` ; const options = { headers : this . getHeaders ( ) } ; return this . http . put ( url , body , options ) . pipe ( map ( res => { if ( ( res as any ) . token ) { this . saveToken ( res ) ; } return res ; } ) ) ; } protected delete ( _path , id ? ) { const url = `${ this . apiEndPoint }${ _path }/${ id }` ; const options = { headers : this . getHeaders ( ) } ; return this . http . delete ( url , options ) . pipe ( map ( res => { if ( ( res as any ) . token ) { this . saveToken ( res ) ; } return res ; } ) ) ; } protected saveToken ( providerResponse ) { return fromPromise ( Promise . resolve ( localStorage . setItem ( STORAGE_ITEM , providerResponse . token ) ) . then ( _ => providerResponse . token ) . catch ( err => err ) ) ; } protected dellToken ( ) { return fromPromise ( Promise . resolve ( localStorage . removeItem ( STORAGE_ITEM ) ) ) ; } checkStorage ( ) { console . warn ( '[Deprecated]: see token-interceptor.ts' ) ; const token = localStorage . getItem ( STORAGE_ITEM ) ; this . tokentStorage = token || '' ; } getHeaders ( ) { const header = new HttpHeaders ( ) . set ( 'cache-control' , 'no-cache' ) ; return header ; } }