]>
Commit | Line | Data |
---|---|---|
1 | import { Injectable } from '@angular/core'; | |
2 | import { | |
3 | ConnectionBackend, | |
4 | Headers, | |
5 | Http, | |
6 | Request, | |
7 | RequestMethod, | |
8 | RequestOptions, | |
9 | RequestOptionsArgs, | |
10 | Response | |
11 | } from '@angular/http'; | |
12 | import { Observable } from 'rxjs/Observable'; | |
13 | ||
14 | import { AuthService } from './auth.service'; | |
15 | ||
16 | @Injectable() | |
17 | export class AuthHttp extends Http { | |
18 | constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private authService: AuthService) { | |
19 | super(backend, defaultOptions); | |
20 | } | |
21 | ||
22 | request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> { | |
23 | if (!options) options = {}; | |
24 | ||
25 | options.headers = new Headers(); | |
26 | this.setAuthorizationHeader(options.headers); | |
27 | ||
28 | return super.request(url, options) | |
29 | .catch((err) => { | |
30 | if (err.status === 401) { | |
31 | return this.handleTokenExpired(url, options); | |
32 | } | |
33 | ||
34 | return Observable.throw(err); | |
35 | }); | |
36 | } | |
37 | ||
38 | delete(url: string, options?: RequestOptionsArgs): Observable<Response> { | |
39 | if (!options) options = {}; | |
40 | options.method = RequestMethod.Delete; | |
41 | ||
42 | return this.request(url, options); | |
43 | } | |
44 | ||
45 | get(url: string, options?: RequestOptionsArgs): Observable<Response> { | |
46 | if (!options) options = {}; | |
47 | options.method = RequestMethod.Get; | |
48 | ||
49 | return this.request(url, options); | |
50 | } | |
51 | ||
52 | post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> { | |
53 | if (!options) options = {}; | |
54 | options.method = RequestMethod.Post; | |
55 | options.body = body; | |
56 | ||
57 | return this.request(url, options); | |
58 | } | |
59 | ||
60 | put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> { | |
61 | if (!options) options = {}; | |
62 | options.method = RequestMethod.Put; | |
63 | options.body = body; | |
64 | ||
65 | return this.request(url, options); | |
66 | } | |
67 | ||
68 | private handleTokenExpired(url: string | Request, options: RequestOptionsArgs) { | |
69 | return this.authService.refreshAccessToken() | |
70 | .flatMap(() => { | |
71 | this.setAuthorizationHeader(options.headers); | |
72 | ||
73 | return super.request(url, options); | |
74 | }); | |
75 | } | |
76 | ||
77 | private setAuthorizationHeader(headers: Headers) { | |
78 | headers.set('Authorization', this.authService.getRequestHeaderValue()); | |
79 | } | |
80 | } |