Move to HttpClient and PrimeNG data table
[oweals/peertube.git] / client / src / app / shared / rest / rest-extractor.service.ts
1 import { Injectable } from '@angular/core'
2 import { Observable } from 'rxjs/Observable'
3 import { HttpErrorResponse } from '@angular/common/http'
4
5 import { Utils } from '../utils'
6 import { ResultList } from '../../../../../shared'
7
8 @Injectable()
9 export class RestExtractor {
10
11   extractDataBool () {
12     return true
13   }
14
15   applyToResultListData <T> (result: ResultList<T>, fun: Function, additionalArgs?: any[]): ResultList<T> {
16     const data: T[] = result.data
17     const newData: T[] = []
18
19     data.forEach(d => newData.push(fun.call(this, d, additionalArgs)))
20
21     return {
22       total: result.total,
23       data: newData
24     }
25   }
26
27   convertResultListDateToHuman <T> (result: ResultList<T>, fieldsToConvert: string[] = [ 'createdAt' ]): ResultList<T> {
28     return this.applyToResultListData(result, this.convertDateToHuman, [ fieldsToConvert ])
29   }
30
31   convertDateToHuman (target: object, fieldsToConvert: string[]) {
32     const source = {}
33     fieldsToConvert.forEach(field => {
34       source[field] = Utils.dateToHuman(target[field])
35     })
36
37     return Object.assign(target, source)
38   }
39
40   handleError (err: HttpErrorResponse) {
41     let errorMessage
42
43     if (err.error instanceof Error) {
44       // A client-side or network error occurred. Handle it accordingly.
45       errorMessage = err.error.message
46       console.error('An error occurred:', errorMessage)
47     } else if (err.status !== undefined) {
48       // The backend returned an unsuccessful response code.
49       // The response body may contain clues as to what went wrong,
50       errorMessage = err.error
51       console.error(`Backend returned code ${err.status}, body was: ${errorMessage}`)
52     } else {
53       errorMessage = err
54     }
55
56     return Observable.throw(errorMessage)
57   }
58 }