File

projects/ngforage/src/lib/cache/ng-forage-cache.service.ts

Description

An extension of NgForage which adds expiration support

Extends

NgForage

Index

Methods
Accessors

Methods

Public clone
clone(config?: NgForageOptions)
Inherited from NgForage
Defined in NgForage:43
Parameters :
Name Type Optional
config NgForageOptions Yes
Returns : NgForageCache
Public Async getCached
getCached(key: string)
Type parameters :
  • T

Retrieve data

Parameters :
Name Type Optional Description
key string No

Data key

Public Async removeCached
removeCached(key: string)

Remove data

Parameters :
Name Type Optional Description
key string No

Data key

Returns : Promise<void>
Public Async setCached
setCached(key: string, data: T, cacheTime: number)
Type parameters :
  • T

Set data

Parameters :
Name Type Optional Default value Description
key string No

Data key

data T No

Data to set

cacheTime number No this.cacheTime

Override cache set in global or instance configCacheConfigurable.cacheTime.

Returns : Promise<T>
Public Async clear
clear()
Inherited from NgForage
Defined in NgForage:34

Removes every key from the database, returning it to a blank slate.

clear() will remove every item in the offline store. Use this method with caution.

Returns : Promise<void>
Public Async dropInstance
dropInstance(cfg?: LocalForageDbInstanceOptions)
Inherited from NgForage
Defined in NgForage:25

When invoked with no arguments, it drops the “store” of the current instance. When invoked with an object specifying both name and storeName properties, it drops the specified “store”. When invoked with an object specifying only a name property, it drops the specified “database” (and all its stores).

Parameters :
Name Type Optional
cfg LocalForageDbInstanceOptions Yes
Returns : Promise<void>
Public Async getItem
getItem(key: string)
Inherited from NgForage
Defined in NgForage:54
Type parameters :
  • T

Gets an item from the storage library. If the key does not exist, getItem() will return null.

Parameters :
Name Type Optional Description
key string No

Data key

Returns : Promise<T | null>
Public Async iterate
iterate(iteratee: (value: T,key: string,iterationNumber: number) => void)
Inherited from NgForage
Defined in NgForage:69
Type parameters :
  • T
  • U

Iterate over all value/key pairs in datastore. iteratee is called once for each pair, with the following arguments:

  1. Value
  2. Key
  3. iterationNumber - one-based number
iterate() supports early exit by returning a non-`undefined` value inside iteratorCallback callback.
Parameters :
Name Type Optional
iteratee function No
Returns : Promise<U>
Public Async key
key(index: number)
Inherited from NgForage
Defined in NgForage:77

Get the name of a key based on its ID.

Parameters :
Name Type Optional
index number No
Returns : Promise<string>
Public Async keys
keys()
Inherited from NgForage
Defined in NgForage:84

Get the list of all keys in the datastore.

Returns : Promise<string[]>
Public Async length
length()
Inherited from NgForage
Defined in NgForage:91

Gets the number of keys in the offline store (i.e. its “length”).

Returns : Promise<number>
Public Async ready
ready()
Inherited from NgForage
Defined in NgForage:100

Even though localForage queues up all of its data API method calls, ready() provides a way to determine whether the asynchronous driver initialization process has finished. That’s useful in cases like when we want to know which driver localForage has settled down using.

Returns : Promise<void>
Public Async removeItem
removeItem(key: string)
Inherited from NgForage
Defined in NgForage:108

Removes the value of a key from the offline store.

Parameters :
Name Type Optional Description
key string No

Data key

Returns : Promise<void>
Public Async setItem
setItem(key: string, data: T)
Inherited from NgForage
Defined in NgForage:134
Type parameters :
  • T

Saves data to an offline store. You can store the following types of JavaScript objects:

  • Array
  • ArrayBuffer
  • Blob
  • Float32Array
  • Float64Array
  • Int8Array
  • Int16Array
  • Int32Array
  • Number
  • Object
  • Uint8Array
  • Uint8ClampedArray
  • Uint16Array
  • Uint32Array
  • String
Parameters :
Name Type Optional Description
key string No

Data key

data T No

Data

Returns : Promise<T>
Public supports
supports(driver: Driver | string)
Inherited from NgForage
Defined in NgForage:142

Check whether the given driver is supported/registered.

Parameters :
Name Type Optional Description
driver Driver | string No

Driver name

Returns : boolean
Public configure
configure(opts: NgForageOptions)
Inherited from BaseConfigurableImpl

Bulk-set configuration options

Parameters :
Name Type Optional Description
opts NgForageOptions No

The configuration

Public toJSON
toJSON()
Inherited from BaseConfigurableImpl
Public toString
toString()
Inherited from BaseConfigurableImpl
Returns : string

Accessors

cacheTime
getcacheTime()

Cache time in milliseconds

Returns : number
setcacheTime(t: number)
Parameters :
Name Type Optional
t number No
Returns : void
import {Injectable} from '@angular/core';
import type {NgForageOptions} from '../config';
import {CacheConfigurable} from '../config';
import {NgForage} from '../main';
import type {CachedItem} from './cached-item';
import {CachedItemImpl} from './cached-item-impl.class';

/** @internal */
interface CacheKeys {
  data: string;

  expiry: string;
}

/** @internal */
function calculateCacheKeys(mainKey: string): CacheKeys {
  return {
    data: `${mainKey}_data`,
    expiry: `${mainKey}_expiry`
  };
}

/**
 * An extension of {@link NgForage} which adds expiration support
 */
@Injectable({providedIn: 'root'})
export class NgForageCache extends NgForage implements CacheConfigurable {

  /**
   * Cache time in milliseconds
   * @default 300000
   */
  public get cacheTime(): number {
    return this.config.cacheTime ?? this.baseConfig.cacheTime;
  }

  public set cacheTime(t: number) {
    this.config.cacheTime = t;
    this.storeNeedsRecalc = true;
  }

  /** @inheritDoc */
  public override clone(config?: NgForageOptions): NgForageCache {
    const inst = new NgForageCache(this.baseConfig, this.fact);
    inst.configure({...this.finalConfig, ...config});

    return inst;
  }

  /**
   * Retrieve data
   * @param key Data key
   */
  public async getCached<T>(key: string): Promise<CachedItem<T>> {
    const keys = calculateCacheKeys(key);

    const [data, expiry] = await Promise
      .all([this.getItem<T>(keys.data), this.getItem<number>(keys.expiry)]);

    return new CachedItemImpl<T>(data!, expiry!);
  }

  /**
   * Remove data
   * @param key Data key
   */
  public async removeCached(key: string): Promise<void> {
    const keys = calculateCacheKeys(key);
    await Promise
      .all([this.removeItem(keys.data), this.removeItem(keys.expiry)]);
  }

  /**
   * Set data
   * @param key Data key
   * @param data Data to set
   * @param [cacheTime] Override cache set in {@link CacheConfigurable#cacheTime global or instance config}.
   */
  public async setCached<T>(key: string, data: T, cacheTime: number = this.cacheTime): Promise<T> {
    const keys = calculateCacheKeys(key);

    const [out] = await Promise
      .all([this.setItem<T>(keys.data, data), this.setItem(keys.expiry, Date.now() + cacheTime)]);

    return out;
  }

  /** @internal */
  public override toJSON(): NgForageOptions {
    return Object.assign(super.toJSON() as NgForageOptions, {cacheTime: this.cacheTime});
  }
}

results matching ""

    No results matching ""