How to create caching service by using interceptor to cache http request, to save in bandwidth  and speed up our up?

Well, here is how!

 

In order to cache requests on Angular side, we will create interceptor caching service where we will cache all GET request (except couple of exceptions) and when user try to load that same resource again it will be served from the cache.

 

So let's first create our  cache.service.ts

                    import { Injectable } from '@angular/core';
import {HttpResponse} from "@angular/common/http";
import {Globals} from "../globals";

@Injectable({
  providedIn: 'root'
})
export class CacheService {

  constructor(
    private globals: Globals,
  ) { }

  private cache:any = {};


  doNotCache = [
    this.globals.apiURL+'logout',
    this.globals.apiURL+'email/verify',
    // ....
  ];

  cacheResponse(responseURL: string, response: HttpResponse<any>):void{
    this.cache[responseURL] = response;
  }

  getCachedResponse(requestURL: string): HttpResponse<any> | null{
    return this.cache[requestURL];
  }

  deleteCachedResponse(requestURL: string){
    this.cache[requestURL] = null;
  }
  clearCache(){
    this.cache = {};
  }
  getAllCached(){
    return this.cache;
  }

  encodeURL(url){
    return encodeURIComponent(url);
  }

  decodeURL(url){
    return decodeURIComponent(url);
  }

  includesDoNotCache(path){

    let url = this.encodeURL(path);

    for (let i = 0; i < this.doNotCache.length;i++){

      if(path.includes(this.doNotCache[i])){

        return true;

      }

    }

    return false;

  }
}

                  

 

 

Now in  our intercept-request.service.ts use this caching service:

                    intercept(request: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {

    // set caching request
      if(request.method !== 'GET'){
         // delete cache on any other request type  - if you want
        //this.cacheService.clearCache();

      }else{
        if(!this.cacheService.includesDoNotCache(request.url)){
          // check do we have this request cached and return it
          const cachedResponse = this.cacheService.getCachedResponse(this.cacheService.encodeURL(request.url));
          if (cachedResponse) {
            console.log("serving from cache");
            return of(cachedResponse);
          }
        }
      }

    // end of caching request

// check response
    return next.handle(request)
      .pipe(
        tap(event => {
          if (event instanceof HttpResponse) {
            // should we cache reqeust?
            if(request.method === 'GET' &&
              !this.cacheService.includesDoNotCache(request.url) &&
              request.url.includes('/api/')
            ){

              this.cacheService.cacheResponse(this.cacheService.encodeURL(request.url), event);

            }
         }
      );

});


                  

 

We can also delete some urls from cache by calling  CacheService.deleteCachedResponse(url) - this can be useful when user change some content in that case we can delete that URL. Another way to delete is when user log out, then we can call CacheService.clearCache();