Matteo Scandolo | 0f77c50 | 2016-12-06 16:46:00 -0800 | [diff] [blame] | 1 | import {Http, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; |
| 2 | import {Injectable} from '@angular/core'; |
| 3 | import {Observable} from 'rxjs'; |
| 4 | import {AuthService} from './auth.service'; |
| 5 | /** |
| 6 | * Created by teone on 12/6/16. |
| 7 | */ |
| 8 | @Injectable() |
| 9 | export class XosHttp { |
| 10 | constructor( |
| 11 | private http: Http, |
| 12 | private authService: AuthService |
| 13 | ) { |
| 14 | } |
| 15 | |
Matteo Scandolo | 40f8fa9 | 2016-12-07 09:21:35 -0800 | [diff] [blame^] | 16 | // TODO intercept non authenticated calls and send to login (remove cookies) |
| 17 | // TODO add POST, PUT, DELETE declaration |
| 18 | get(url: string, options?: RequestOptionsArgs): Observable<Response> { |
| 19 | |
| 20 | options = this.checkOptions(options); |
| 21 | options = this.getHeaders(options); |
| 22 | options = this.getParams(options); |
| 23 | |
| 24 | return this.http.get(url, options); |
| 25 | } |
| 26 | |
Matteo Scandolo | 0f77c50 | 2016-12-06 16:46:00 -0800 | [diff] [blame] | 27 | private checkOptions(options?: RequestOptionsArgs): RequestOptionsArgs { |
| 28 | // if options are not there, create them |
Matteo Scandolo | 40f8fa9 | 2016-12-07 09:21:35 -0800 | [diff] [blame^] | 29 | if (!options) { |
Matteo Scandolo | 0f77c50 | 2016-12-06 16:46:00 -0800 | [diff] [blame] | 30 | options = {}; |
| 31 | } |
| 32 | return options; |
| 33 | } |
| 34 | |
| 35 | private getHeaders(options: RequestOptionsArgs): RequestOptionsArgs { |
| 36 | // add auth headers |
| 37 | options.headers = this.authService.getUserHeaders(); |
| 38 | return options; |
| 39 | } |
| 40 | |
| 41 | private getParams(options: RequestOptionsArgs): RequestOptionsArgs { |
| 42 | // add the no_hyperlinks param |
| 43 | if (!options.search) { |
| 44 | options.search = new URLSearchParams(); |
| 45 | } |
| 46 | |
| 47 | if (options.search instanceof URLSearchParams) { |
| 48 | options.search.set('no_hyperlinks', '1'); |
| 49 | } |
| 50 | else if (typeof options.search === 'string') { |
| 51 | options.search += '&no_hyperlinks=1'; |
| 52 | } |
| 53 | return options; |
| 54 | } |
Matteo Scandolo | 0f77c50 | 2016-12-06 16:46:00 -0800 | [diff] [blame] | 55 | } |