File

C:/GoDev/src/TCSTK-Angular/projects/tibco-tcstk/tc-core-lib/src/lib/interceptors/caching-interceptor.ts

Index

Methods

Constructor

constructor(cache: RequestCacheService)
Parameters :
Name Type Optional
cache RequestCacheService No

Methods

intercept
intercept(req: HttpRequest, next: HttpHandler)
Parameters :
Name Type Optional
req HttpRequest<any> No
next HttpHandler No
Returns : any
sendRequest
sendRequest(req: HttpRequest, next: HttpHandler, cache: RequestCacheService)
Parameters :
Name Type Optional
req HttpRequest<any> No
next HttpHandler No
cache RequestCacheService No
Returns : Observable<HttpEvent<any>>
import { Injectable } from '@angular/core';
import { HttpEvent, HttpRequest, HttpResponse, HttpInterceptor, HttpHandler } from '@angular/common/http';

import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { RequestCacheService } from '../services/request-cache.service';

@Injectable()
export class CachingInterceptor implements HttpInterceptor {
  constructor(private cache: RequestCacheService) {}
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    let cachedResponse;
    if (req.headers.get('cacheResponse') || (req.urlWithParams.substr(0, 15)) === '../assets/icons') {
      // only cache if the cacheResponse flag is set
      if (!req.headers.get('flushCache')) {
        cachedResponse = this.cache.get(req);
      } else {
      }
      // use the cache
    } else {
      // dont pass the cache since this should not be cached
      return this.sendRequest(req, next, undefined);
    }
    // return cached response or make request if no cached response
    return cachedResponse ? of(cachedResponse) : this.sendRequest(req, next, this.cache);
  }

  sendRequest(
    req: HttpRequest<any>,
    next: HttpHandler,
    cache: RequestCacheService): Observable<HttpEvent<any>> {
    return next.handle(req)
      .pipe(
      tap(event => {
        if (event instanceof HttpResponse && cache) {
          cache.put(req, event);
        }
      })
    );
  }
}

result-matching ""

    No results matching ""