Skip to content

Instantly share code, notes, and snippets.

@stevermeister
Created July 18, 2017 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevermeister/6281f22550250db7d57ef0497ccb4c02 to your computer and use it in GitHub Desktop.
Save stevermeister/6281f22550250db7d57ef0497ccb4c02 to your computer and use it in GitHub Desktop.
import { Inject, Injectable } from '@angular/core';
import {
BaseRequestOptions,
Headers,
Http,
Request,
RequestOptionsArgs,
Response,
URLSearchParams,
XHRBackend
} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/publishLast';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/throw';
import { BASE_URL } from '../shared/config';
@Injectable()
export class RequestOptionsService extends BaseRequestOptions {
public constructor(
@Inject(BASE_URL) private _BASE_URL: string
) {
super();
}
public merge(options: RequestOptionsArgs): BaseRequestOptions {
if (!options.headers) {
options.headers = new Headers({});
}
options.url = `${this._BASE_URL}${options.url}`;
options.headers.append('X-Academy-Subdomain', window.location.host.split('.').slice(-3, -2)[0]);
options.headers.append('X-Token', this._getCookie('accessToken'));
return super.merge(options);
}
private _getCookie(name: string): string {
const normalizedName: string = name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1');
const regExp: RegExp = new RegExp(`(?:^|; )${normalizedName}=([^;]*)`);
const matches: RegExpMatchArray | null = document.cookie.match(regExp);
return matches ? decodeURIComponent(matches[1]) : '';
}
}
@Injectable()
export class HttpService extends Http {
private _currentAcademy$: Observable<Academy>;
private _errorSubject$$: Subject<Response> = new Subject();
private _errorStream$: Observable<Response>;
public constructor(
_backend: XHRBackend,
_defaultOptions: BaseRequestOptions
) {
super(_backend, _defaultOptions);
this._currentAcademy$ = this._getCurrentAcademy();
this._errorStream$ = this._errorSubject$$.asObservable();
}
public getAuthErrorStream(): Observable<Response> {
return this._errorStream$;
}
public request(request: Request): Observable<Response> {
return super.request(request)
.catch((error: Response) => this._handle401Error(error));
}
public get(url: string, params: QueryParams = {}): Observable<Response> {
return this._currentAcademy$
.switchMap((academy: Academy) => {
params['academyId'] = academy.id;
return super.get(url, { search: this._createUrlSearchParams(params) });
});
}
/* tslint:disable */
public post(url: string, body: any): Observable<Response> {
return this.request(new Request(this._defaultOptions.merge({ body, url, method: 'POST' })));
}
public patch(url: string, body: any): Observable<Response> {
return this.request(new Request(this._defaultOptions.merge({ body, url, method: 'PATCH' })));
}
public delete(url: string, body: any): Observable<Response> {
return this.request(new Request(this._defaultOptions.merge({ body, url, method: 'DELETE' })));
}
/* tslint:enable */
public getJSON<T>(url: string, params: QueryParams = {}): Observable<T> {
return this.get(url, params)
.map((res: Response) => res.json());
}
public getResponse<T>(url: string, params: QueryParams = {}): Observable<CustomResponse<T>> {
return this.get(url, params)
.map((res: Response) => ({
data: res.json(),
headers: res.headers
}));
}
public postJSON<T>(url: string, body: Object): Observable<T> {
return this.post(url, body)
.map((res: Response) => res.json());
}
public patchJSON<T>(url: string, body: Object): Observable<T> {
return this.patch(url, body)
.map((res: Response) => res.json());
}
public deleteJSON<T>(url: string, body: Object): Observable<T> {
return this.delete(url, body)
.map((res: Response) => res.json());
}
public getCurrentAcademy(): Observable<Academy> {
return this._currentAcademy$;
}
private _getCurrentAcademy(): Observable<Academy> {
const subdomain: string = window.location.host.split('.').slice(-3, -2)[0];
return super.get(`academies?subdomain=${subdomain}`)
.map((res: Response) => res.json())
.map((academies: Academy[]) => academies[0])
.publishLast()
.refCount();
}
private _createUrlSearchParams(obj: QueryParams): URLSearchParams {
const searchParams: URLSearchParams = new URLSearchParams();
Object.keys(obj).forEach((key: string) => {
const value: QueryParam | QueryParam[] = obj[key];
if (!value) {
return;
}
if (value instanceof Array) {
value.forEach((part: string) => {
searchParams.append(`${key}[]`, String(part));
});
} else {
searchParams.set(key, String(value));
}
});
return searchParams;
}
private _handle401Error(response: Response): Observable<Response> {
if (response.status === 401) {
this._errorSubject$$.next(response);
}
return Observable.throw(response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment