JSFiddle - React, Tailwind, and code Playground

by nomadev

TypeScript

import { ConfigService, CACHE_TTL, CACHE_SIZE } from '../services/config.service';
import { Injectable } from '@angular/core';
import { HttpEvent, HttpResponse } from '@angular/common/http';
import { RequestCacheService } from '../modules/shared/services/request-cache.service';

import { Observable, throwError } from 'rxjs';
import { tap, shareReplay, catchError } from 'rxjs/operators';

import {
    HttpRequest,
    HttpHandler,
    HttpInterceptor
} from '@angular/common/http';



/**
  providedIn: 'root' garantisce che questo servizio sia
  risolto dal root-injector. tutti i servizi provided nel root-injector
  vengono istanziati durante il bootstrap dell'app e prima di qualsiasi altro
  provider non registrato sul RI.
*/
@Injectable({
    providedIn: 'root'
})
export class CacheInterceptor implements HttpInterceptor {

    constructor(private cache: RequestCacheService, private config: ConfigService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler) {

        /**
         * We cache only GET CALLS
         */
        if (req.method === 'GET') {
            const cachedResponse$ = this.cache.get(req.url);

            if (cachedResponse$ instanceof Observable)
                return cachedResponse$;
            else {
                const SIZE = this.config.constants.get(CACHE_SIZE);

                const xhrRequest$ = this.cacheRequest(req, next)
                                    /**
                                     * we need to share an 'hot' Observable, so that
                                     * many subscriptions will not trigger
                                     * many HttpRequests
                                     */
                                    .pipe(
                                        /**
                                         * This operator returns an Observable that shares a single
                                         * subscription to the underlying source, which is the Observable
                    ...