]>
Commit | Line | Data |
---|---|---|
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 | // A server-side error occurred. | |
49 | // TODO: remove when angular/angular#19477 (comment) is fixed | |
50 | let body = JSON.parse(err.error) | |
51 | if (body) { | |
52 | if (body.errors) { | |
53 | const errors = body.errors | |
54 | const error = errors[Object.keys(errors)[0]] | |
55 | errorMessage = error.msg // Take the message of the first error | |
56 | } else if (body.error) { | |
57 | errorMessage = body.error | |
58 | } | |
59 | } | |
60 | errorMessage = errorMessage ? errorMessage : 'Unknown error.' | |
61 | console.error(`Backend returned code ${err.status}, body was: ${errorMessage}`) | |
62 | } else { | |
63 | errorMessage = err | |
64 | } | |
65 | ||
66 | const errorObj = { | |
67 | message: errorMessage, | |
68 | status: undefined, | |
69 | body: undefined | |
70 | } | |
71 | ||
72 | if (err.status) { | |
73 | errorObj.status = err.status | |
74 | errorObj.body = err.error | |
75 | } | |
76 | ||
77 | return Observable.throw(errorObj) | |
78 | } | |
79 | } |