Project

General

Profile

1
import {Inject, Injectable, InjectionToken, PLATFORM_ID} from '@angular/core';
2
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
3
import { Observable } from 'rxjs';
4
import { timeout } from 'rxjs/operators';
5
import {isPlatformServer} from "@angular/common";
6
import {properties} from "../../environments/environment";
7
import {isArray} from "util";
8

    
9
export const DEFAULT_TIMEOUT = new InjectionToken<number>('defaultTimeout');
10

    
11
@Injectable()
12
export class TimeoutInterceptor implements HttpInterceptor {
13
  private static TIMEOUT_WHITELIST = [properties.csvAPIURL];
14

    
15
  constructor(@Inject(DEFAULT_TIMEOUT) protected defaultTimeout: number, @Inject(PLATFORM_ID) private platformId: any) {
16
  }
17

    
18
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
19
    if (req.method !== 'GET' || this.isService(req, TimeoutInterceptor.TIMEOUT_WHITELIST)) {
20
      return next.handle(req);
21
    }
22

    
23
    const timeoutValue = isPlatformServer(this.platformId)?3000:6000;//req.headers.get('timeout') || this.defaultTimeout;
24
    const timeoutValueNumeric = Number(timeoutValue);
25
    return next.handle(req).pipe(timeout(timeoutValueNumeric));
26
  }
27

    
28
  isService(req: HttpRequest<any>, service: string | string[]):boolean {
29
    if(isArray(service)) {
30
      return !!service.find(element => req.url.indexOf(element) !== -1);
31
    } else {
32
      return req.url.indexOf(service) !== -1;
33
    }
34
  }
35
}
(4-4/4)