1 import { Injectable } from '@angular/core'
2 import { Observable } from 'rxjs/Observable'
3 import { HttpErrorResponse } from '@angular/common/http'
5 import { Utils } from '../utils'
6 import { ResultList } from '../../../../../shared'
9 export class RestExtractor {
15 applyToResultListData <T> (result: ResultList<T>, fun: Function, additionalArgs?: any[]): ResultList<T> {
16 const data: T[] = result.data
17 const newData: T[] = []
19 data.forEach(d => newData.push(fun.call(this, d, additionalArgs)))
27 convertResultListDateToHuman <T> (result: ResultList<T>, fieldsToConvert: string[] = [ 'createdAt' ]): ResultList<T> {
28 return this.applyToResultListData(result, this.convertDateToHuman, [ fieldsToConvert ])
31 convertDateToHuman (target: object, fieldsToConvert: string[]) {
33 fieldsToConvert.forEach(field => {
34 source[field] = Utils.dateToHuman(target[field])
37 return Object.assign(target, source)
40 handleError (err: HttpErrorResponse) {
45 if (err.error instanceof Error) {
46 // A client-side or network error occurred. Handle it accordingly.
47 errorMessage = err.error.message
48 console.error('An error occurred:', errorMessage)
49 } else if (err.status !== undefined) {
50 const body = err.error
51 errorMessage = body.error
52 console.error(`Backend returned code ${err.status}, body was: ${errorMessage}`)
58 message: errorMessage,
63 errorObj.status = err.status
66 return Observable.throw(errorObj)