-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathhttp.service.ts
More file actions
51 lines (44 loc) 路 1.93 KB
/
Copy pathhttp.service.ts
File metadata and controls
51 lines (44 loc) 路 1.93 KB
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
import { Injectable } from '@angular/core';
import { IDocumentResource } from '../interfaces/data-object';
import { HttpClient, HttpHeaders, HttpEvent } from '@angular/common/http';
import { JsonapiConfig } from '../jsonapi-config';
import { share, tap } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { IDocumentData } from '../interfaces/document';
@Injectable()
export class Http {
// NOTE: GET requests are stored in a this object to prevent duplicate requests
public get_requests: { [key: string]: Observable<IDocumentData> } = {};
public constructor(private http: HttpClient, private rsJsonapiConfig: JsonapiConfig) {}
public exec(path: string, method: string, data?: IDocumentResource): Observable<IDocumentData> {
let req: { body: IDocumentResource | null; headers: HttpHeaders } = {
body: data || null,
headers: new HttpHeaders({
'Content-Type': 'application/vnd.api+json',
Accept: 'application/vnd.api+json'
})
};
let old_time = Date.now()
// NOTE: prevent duplicate GET requests
if (method === 'get') {
if (!this.get_requests[path]) {
let obs: Observable<IDocumentData> = this.http.request<IDocumentData>(method, this.rsJsonapiConfig.url + path, req).pipe(
tap(() => {
console.log('El tiempo en el metodo original exec ----->', Date.now() - old_time)
delete this.get_requests[path];
}),
share()
);
this.get_requests[path] = obs;
return obs;
}
return this.get_requests[path];
}
return this.http.request<IDocumentData>(method, this.rsJsonapiConfig.url + path, req).pipe(
tap(() => {
delete this.get_requests[path];
}),
share()
);
}
}