Example #1
0
    hydrate: flow(function* () {

      if (__DEV__) {
        // Inspect individual models
        makeInspectable(self);
        makeInspectable(Movies);
        makeInspectable(InTheaters);
        makeInspectable(Genres);
      }

      const storageKey = 'Store.settings';
      const data = JSON.parse(yield AsyncStorage.getItem(storageKey));
      if (data) {
        applySnapshot(self.settings, data);
      }

      onSnapshot(self.settings, debounce(
        snapshot => AsyncStorage.setItem(storageKey, JSON.stringify(snapshot)),
        1200,
      ));

      // Load all supplimental data
      Genres.loadAllGenres();
      Cinemas.loadAllCinemas();

      self.isHydrated = true;
    }),
 /**
  * check wether item is expired
  * @private
  * @param key - the key of the item
  * 
  * @return true if the item is expired.
  */
 async _isExpired(key) {
   const text = await AsyncStorage.getItem(key);
   const item = JSON.parse(text);
   if (getCurrTime() >= item.expires) {
     return true;
   }
   return false;
 }
Example #3
0
  public getProgress(id: string) {
    return AsyncStorage.getItem(this.getKey(id)).then(data => {
      if (!data) {
        return {};
      }

      return JSON.parse(data) as ISerializedProgress;
    });
  }
  /**
   * Set item into cache. You can put number, string, boolean or object.
   * The cache will first check whether has the same key.
   * If it has, it will delete the old item and then put the new item in
   * The cache will pop out items if it is full
   * You can specify the cache item options. The cache will abort and output a warning:
   * If the key is invalid
   * If the size of the item exceeds itemMaxSize.
   * If the value is undefined
   * If incorrect cache item configuration
   * If error happened with browser storage
   * 
   * @param {String} key - the key of the item
   * @param {Object} value - the value of the item
   * @param {Object} [options] - optional, the specified meta-data
   * @return {Prmoise}
   */
  async setItem(key, value, options) {
    logger.debug(`Set item: key is ${key}, value is ${value} with options: ${options}`);
    const prefixedKey = this.config.keyPrefix + key;
    // invalid keys
    if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
      logger.warn(`Invalid key: should not be empty or 'CurSize'`);
      return;
    }
    
    if ((typeof value) === 'undefined') {
      logger.warn(`The value of item should not be undefined!`);
      return;
    }

    const cacheItemOptions = {
      priority: options && options.priority !== undefined ? options.priority : this.config.defaultPriority,
      expires: options && options.expires !== undefined ? options.expires : (this.config.defaultTTL + getCurrTime())
    };

    if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
      logger.warn(`Invalid parameter: priority due to out or range. It should be within 1 and 5.`);
      return;
    }

    const item = this.fillCacheItem(prefixedKey, value, cacheItemOptions);
    
    // check wether this item is too big;
    if (item.byteSize > this.config.itemMaxSize) {
      logger.warn(`Item with key: ${key} you are trying to put into is too big!`);
      return;
    }

    try {
      // first look into the storage, if it exists, delete it.
      const val = await AsyncStorage.getItem(prefixedKey);
      if (val) {
        await this._removeItem(prefixedKey, JSON.parse(val).byteSize);
      }


      // check whether the cache is full
      if (await this._isCacheFull(item.byteSize)) {
        const validKeys = await this._findValidKeys();
        if (await this._isCacheFull(item.byteSize)) {
          const sizeToPop = await this._sizeToPop(item.byteSize);
          await this._popOutItems(validKeys, sizeToPop);
        }
      }

      // put item in the cache
      await this._setItem(prefixedKey, item);
    } catch (e) {
      logger.warn(`setItem failed! ${e}`);
    }
  }
  public getConsent() {
    return AsyncStorage.getItem(DataPolicyConsentStorage.getKey()).then(
      data => {
        if (!data) {
          return undefined;
        }

        return JSON.parse(data) as IDataPolicyConsent;
      }
    );
  }
  /**
   * delete item from cache
   * @private
   * @param prefixedKey - the key of the item
   * @param size - optional, the byte size of the item
   */
  async _removeItem(prefixedKey, size?) {
    const itemSize = size? size : (JSON.parse(await AsyncStorage.getItem(prefixedKey))).byteSize;
    // first try to update the current size of the cache
    await this._decreaseCurSizeInBytes(itemSize);

    // try to remove the item from cache
    try {
      await AsyncStorage.removeItem(prefixedKey);
    } catch (removeItemError) {
      // if some error happened, we need to rollback the current size
      await this._increaseCurSizeInBytes(itemSize);
      logger.error(`Failed to remove item: ${removeItemError}`);
    }
  }
  /**
   * remove item from the cache
   * The cache will abort output a warning:
   * If error happened with AsyncStorage
   * @param {String} key - the key of the item
   * @return {Promise}
   */
  async removeItem(key) {
    logger.debug(`Remove item: key is ${key}`);
    const prefixedKey = this.config.keyPrefix + key;

    if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
      return;
    }

    try {
      const val = await AsyncStorage.getItem(prefixedKey);
      if (val) {
        await this._removeItem(prefixedKey, JSON.parse(val).byteSize);
      }
    } catch (e) {
      logger.warn(`removeItem failed! ${e}`);
    }
  }
  /**
   * Get item from cache. It will return null if item doesn’t exist or it has been expired.
   * If you specified callback function in the options, 
   * then the function will be executed if no such item in the cache 
   * and finally put the return value into cache. 
   * Please make sure the callback function will return the value you want to put into the cache.
   * The cache will abort output a warning:
   * If the key is invalid
   * If error happened with AsyncStorage
   * 
   * @param {String} key - the key of the item
   * @param {Object} [options] - the options of callback function
   * @return {Promise} - return a promise resolves to be the value of the item
   */
  async getItem(key, options) {
    console.log(`Get item: key is ${key} with options ${options}`);
    let ret = null;
    const prefixedKey = this.config.keyPrefix + key;

    if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
      logger.warn(`Invalid key: should not be empty or 'CurSize'`);
      return null;
    }

    try {
      ret = await AsyncStorage.getItem(prefixedKey);
      if (ret != null) {
        if (await this._isExpired(prefixedKey)) {
          // if expired, remove that item and return null
          await this._removeItem(prefixedKey, JSON.parse(ret).byteSize);
        } else {
          // if not expired, great, return the value and refresh it
          let item = JSON.parse(ret);
          item = await this._refreshItem(item, prefixedKey);
          return item.data;
        }
      }

      if (options && options.callback !== undefined ) {
        const val = options.callback();
        if (val !== null) {
          this.setItem(key, val, options);
        }
        return val;
      }
      return null;
    } catch (e) {
      logger.warn(`getItem failed! ${e}`);
      return null;
    }
  }
Example #9
0
 static get(key) {
   return AsyncStorage.getItem(key).then(function(value) {
     return JSON.parse(value)
   })
 }
Example #10
0
export async function getDownloadedTracks (): Promise<ITrack[]> {
  const tracks = await AsyncStorage.getItem(DOWNLOADED_TRACKS)
  return tracks ? JSON.parse(tracks) : []
}