This repository has been archived by the owner on Jan 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
interceptable-http-proxy.service.ts
81 lines (63 loc) · 2.52 KB
/
interceptable-http-proxy.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { Injectable } from '@angular/core';
import { Http, XHRBackend, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { HttpInterceptorService } from './http-interceptor.service';
import { identityFactory, safeProxy } from './util';
@Injectable()
export class InterceptableHttpProxyService implements ProxyHandler<any> {
private static _callStack: string[] = [];
private static _extractUrl(url: any[]): string {
const dirtyUrl: string & { url: string } = url[0];
return typeof dirtyUrl === 'object' && 'url' in dirtyUrl ? dirtyUrl.url : dirtyUrl;
}
constructor(private http: Http, private httpInterceptorService: HttpInterceptorService) {
}
get(target: any, p: PropertyKey, receiver: any): any {
InterceptableHttpProxyService._callStack.push(<string>p);
return receiver;
}
apply(target: any, thisArg: any, argArray?: any): any {
const method = InterceptableHttpProxyService._callStack.pop();
// Comply with strict null checks
if (!method) {
return Observable.empty();
}
// create a object without prototype as the context object
const context = Object.create(null);
return this.httpInterceptorService
._interceptRequest(InterceptableHttpProxyService._extractUrl(argArray), method, argArray, context)
.switchMap(args => {
// Check for request cancellation
if (!args) {
return Observable.empty();
}
const response = this.http[method].apply(this.http, args);
return this.httpInterceptorService._interceptResponse(
InterceptableHttpProxyService._extractUrl(args), method, response, context);
});
}
}
export const _proxyTarget = () => null;
// Make sure all Http methods are known for Proxy Polyfill
Object.keys(Http.prototype).forEach(method => _proxyTarget[method] = `Http.${method}`);
export function _proxyFactory(http, interceptor) {
return safeProxy(_proxyTarget, new InterceptableHttpProxyService(http, interceptor));
}
export function proxyFactory(backend, options, interceptor) {
return _proxyFactory(new Http(backend, options), interceptor);
}
export const InterceptableHttpProxyProviders = [
{
provide: Http,
useFactory: proxyFactory,
deps: [XHRBackend, RequestOptions, HttpInterceptorService]
},
identityFactory(InterceptableHttpProxyService, Http),
];
export const InterceptableHttpProxyNoOverrideProviders = [
{
provide: InterceptableHttpProxyService,
useFactory: _proxyFactory,
deps: [Http, HttpInterceptorService]
}
];