openaire-library/timeout-interceptor.service.ts

35 lines
1.4 KiB
TypeScript
Raw Normal View History

import {Inject, Injectable, InjectionToken, PLATFORM_ID} from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { timeout } from 'rxjs/operators';
import {isPlatformServer} from "@angular/common";
import {properties} from "../../environments/environment";
export const DEFAULT_TIMEOUT = new InjectionToken<number>('defaultTimeout');
@Injectable()
export class TimeoutInterceptor implements HttpInterceptor {
2021-09-07 09:51:07 +02:00
private static TIMEOUT_WHITELIST = [properties.csvAPIURL, properties.registryUrl];
constructor(@Inject(DEFAULT_TIMEOUT) protected defaultTimeout: number, @Inject(PLATFORM_ID) private platformId: any) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.method !== 'GET' || this.isService(req, TimeoutInterceptor.TIMEOUT_WHITELIST)) {
return next.handle(req);
}
const timeoutValue = isPlatformServer(this.platformId)?3000:6000;//req.headers.get('timeout') || this.defaultTimeout;
const timeoutValueNumeric = Number(timeoutValue);
return next.handle(req).pipe(timeout(timeoutValueNumeric));
}
isService(req: HttpRequest<any>, service: string | string[]):boolean {
2021-09-07 09:51:07 +02:00
if(Array.isArray(service)) {
return !!service.find(element => req.url.indexOf(element) !== -1);
} else {
return req.url.indexOf(service) !== -1;
}
}
}