3

I am working in an Ionic 2 project, and recently implemented Ionic Storage. I'm using this in combination with an http interceptor to cache and retry failed api calls. This is done with the assumption that in the event of a loss of connectivity we will cache outgoing requests, and retry them when our connection is regained.

All this functions as hoped. However, since we are going to be retrying failed calls automatically, we are looking to set an expiration on the data saved in the cache. Looking through the Ionic Framework documentation here this doesn't seem to be built in. I was hoping to get some input from other people that may have implemented something similar.

Below is my ionic storage provider, which handles all of my local storage within the app.

Ionic Storage Provider

import { BaseProvider } from './base-provider';
import {Injectable} from '@angular/core';
import { Storage } from '@ionic/storage';
import { CommonExpressions as cmp } from '@drivetime/common-expressions';
import { ICacheQueue } from '../interfaces/cache-queue-typings';

    /*
      Simple provider class to allow for caching of data locally for device or browser.
    */
    const CACHE_KEY = `cacheKey`;
    @Injectable()
    export class IonicStorageProvider {

      constructor(public storage: Storage) {

      }

      pushDataToCache(key: string, data: any) : void {
        this.pushDataToStorageFactory(CACHE_KEY, key, data);
      }

      private pushDataToStorageFactory(storeKey: string, key: string, data: any) : void {
        this.storage.get(storeKey).then((cacheObj: Array<any>) => {
              if (cmp.isDefinedAndNotNull(cacheObj)) {
                cacheObj.push({key, data});
                this.storage.remove(storeKey).then(() => {  
                  this.storage.set(storeKey, cacheObj);              
                });
              } else {
                this.storage.set(storeKey, [{key, data}]);
              }
         });
      }

      getDataFromCache() : Promise<ICacheQueue[]> {
        return this.storage.get(CACHE_KEY);
      }

      resetDataFromCache(): Promise<any> {
        return this.storage.set(CACHE_KEY, []);
      }

      removeDataFromCache(key: string) : Promise<any> {
        return this.storage.remove(key);
      }

      resetCacheQueue(): Promise<boolean> {
        return this.removeDataFromCache(CACHE_KEY)
        .then(() => {
          return this.resetCacheQueue();
        });
      }

      processCacheQueue(baseProvider: BaseProvider): void {
        this.getDataFromCache().then((value: ICacheQueue[]) => {
          if (cmp.isEmpty(value)) {
            value.forEach((cacheObj: ICacheQueue) => {
              baseProvider.retryRequestWithoutCache(cacheObj.request);
            });
            this.resetCacheQueue();
          }
        });
      }
    }
jjohnson8
  • 321
  • 1
  • 3
  • 12

0 Answers0