import { BaseResourceModel } from "../models/base-resource.model" ; import { Injector } from "@angular/core" ; import { HttpClient } from "@angular/common/http" ; import { Observable , throwError } from "rxjs" ; import { map , catchError } from "rxjs/operators" ; export abstract class BaseResourceService < T extends BaseResourceModel > { protected http : HttpClient ; constructor ( protected apiPath , protected injector , protected jsonDataToResourceFn ) { this . http = injector . get ( HttpClient ) ; } getAll ( ) { return this . http . get ( this . apiPath ) . pipe ( map ( this . jsonDataToResources . bind ( this ) ) , catchError ( this . handleError ) ) ; } getById ( id ) { const url = `${ this . apiPath }/${ id }` ; return this . http . get ( url ) . pipe ( map ( this . jsonDataToResource . bind ( this ) ) , catchError ( this . handleError ) ) ; } create ( resource ) { return this . http . post ( this . apiPath , resource ) . pipe ( map ( this . jsonDataToResource . bind ( this ) ) , catchError ( this . handleError ) ) ; } update ( resource ) { const url = `${ this . apiPath }/${ resource . id }` ; return this . http . put ( url , resource ) . pipe ( map ( ( ) => resource ) , catchError ( this . handleError ) ) ; } delete ( id ) { const url = `${ this . apiPath }/${ id }` ; return this . http . delete ( url ) . pipe ( map ( ( ) => null ) , catchError ( this . handleError ) ) ; } protected jsonDataToResources ( jsonData ) { const resources = [ ] ; jsonData . forEach ( element => resources . push ( this . jsonDataToResourceFn ( element ) ) ) ; return resources ; } protected jsonDataToResource ( jsonData ) { return this . jsonDataToResourceFn ( jsonData ) ; } protected handleError ( error ) { console . log ( "ERRO NA REQUISIÇÃO => " , error ) ; return throwError ( error ) ; } }