How to use idb-keyval - 10 common examples

To help you get started, we’ve selected a few idb-keyval examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dcaslin / d2-checklist / src / app / service / destiny-cache.service.ts View on Github external
private async init() {
    this.checkingCache.next(true);
    const t0 = performance.now();
    console.log('Loading cache');
    try {
      const key = 'manifest-' + env.versions.app;
      const manifest = await get(key);
      this.checkingCache.next(false);
      // if nothing found, perhaps version has changed, clear old values
      if (manifest == null) {
        const ks = await keys();
        for (const k of ks) {
          if (k.toString().startsWith('manifest')) {
            del(k);
          }
        }
        await this.load(key);
      } else {
        this.cache = manifest;
      }
      this.percent.next(100);
      this.ready.next(true);
      const t1 = performance.now();
      console.log((t1 - t0) + ' ms to load manifest');


    } catch (exc) {
github ipfs-shipyard / service-worker-gateway / src / index.js View on Github external
.then((ipfs) => {
      ipfsNode = ipfs

      // Keep a record of the start date and time of the IPFS Node
      const d = new Date()

      set('fetched-cids', [])
      set('start-date-time', {
        date: getFormattedDate(d),
        time: getFormattedTime(d)
      })
    })
    .catch((err) => console.err(err))
github forabi / WebCeph / src / store / middleware / persistence.ts View on Github external
async (action: GenericAction) => {
    if (isActionOfType(action, 'LOAD_PERSISTED_STATE_REQUESTED')) {
      console.info('Requested loading persisted state');
      next(action);
      try {
        const keys = await idb.keys();
        let restoredState: RestoredState = { };
        if (keys.length === 0) {
          console.info('No persisted state was found.');
        } else if (indexOf(keys, __VERSION__) > -1) {
          console.info(`Found persisted state compatible with this version (${__VERSION__})`);
          restoredState = await idb.get(__VERSION__);
        } else {
          console.info(
            `Could not find persisted state compatible with this ` +
            `version (${__VERSION__}). Upgrading...`,
          );
          next(persistStateUpgradeStarted(void 0));
          // @TODO: perform any necessary upgrade operations
          await idb.clear(); // @FIXME: Workaround
          // @NOTE: Do not break on switch cases.
          switch (__VERSION__) {
github dcaslin / d2-checklist / src / app / service / wishlist.service.ts View on Github external
private async load(overridePveUrl: string, overridePvpUrl: string): Promise {
    const t0 = performance.now();

    const key = 'wishlist-' + env.versions.app + '-' + overridePveUrl + '-' + overridePvpUrl;
    let rolls: CuratedRoll[] = await get(key);
    if (rolls == null || rolls.length==0) {
      console.log('    No cached wishlists: ' + key);

      // clear cache
      const ks = await keys();
      for (const k of ks) {
        if (k.toString().startsWith('wishlist')) {
          del(k);
        }
      }
      const pveRolls = await this.loadSingle('pve', overridePveUrl, WishlistService.DEFAULT_PVE_URL);
      const pvpRolls = await this.loadSingle('pvp', overridePvpUrl, WishlistService.DEFAULT_PVP_URL);
      rolls = pveRolls.concat(pvpRolls);
      set(key, rolls);
      console.log('    Wishlists downloaded, parsed and saved.');
    } else {
      console.log('    Using cached wishlists: ' + key);
    }
    const t1 = performance.now();
    console.log((t1 - t0) + ' ms to load wishlists');
    return rolls;
github jpodwys / preact-journal / client / js / app-state / index.js View on Github external
const observe = (obj, prop, next, prev) => {
  switch(prop) {
    case 'view': {
      // obj.entry = undefined;
      obj.dialogMode = '';
      if(prev === '/search' && next === '/entries'){
        fire('clearFilters');
      }
      return;
    }
    case 'entries': {
      obj.entries = sortObjectsByDate(next);
      set('entries', obj.entries);
      return;
    }
    case 'dark':        {
      localStorage.setItem('dark', !!next);
      const func = next ? 'add' : 'remove';
      document.body.classList[func]('dark');
      return;
    }
    case 'timestamp':   localStorage.setItem('timestamp', next);   return;
  }
};
github DestinyItemManager / DIM / src / app / inventory / advanced-write-actions.ts View on Github external
export async function getAwaToken(
  account: DestinyAccount,
  action: AwaType,
  item?: D2Item
): Promise {
  if (!awaCache) {
    // load from cache first time
    awaCache = (await get('awa-tokens')) || {};
  }

  let info = awaCache[action];
  if (!info || !tokenValid(info)) {
    try {
      // Note: Error messages should be handled by other components. This is just to tell them to check the app.
      showNotification({
        type: 'info',
        title: t('AWA.ConfirmTitle'),
        body: t('AWA.ConfirmDescription')
      });

      info = awaCache[action] = {
        ...(await requestAdvancedWriteActionToken(account, action, item)),
        used: 0
      };
github facebookarchive / atom-ide-ui / modules / atom-ide-ui / pkg / atom-ide-terminal / lib / main.js View on Github external
async function openTerminalInNewPaneItem(
  options: atom$WorkspaceOpenOptions & {
    terminalInfo: TerminalInfo,
  },
): Promise {
  const existingPane = atom.workspace.paneForURI(TERMINAL_URI);

  // TODO: The flow types are wrong. paneForURI returns a nullable pane
  if (!existingPane) {
    // eslint-disable-next-line nuclide-internal/atom-apis
    return atom.workspace.open(TERMINAL_URI, options);
  }

  const [item, hasShownNux] = await Promise.all([
    atom.workspace.createItemForURI(TERMINAL_URI, options),
    AsyncStorage.get(MOVED_TERMINAL_NUX_SHOWN_KEY),
  ]);
  existingPane.activateItem(item);
  existingPane.activate();

  if (!hasShownNux) {
    invariant(item instanceof TerminalView);
    showTooltipForPaneItem(item);
    AsyncStorage.set(MOVED_TERMINAL_NUX_SHOWN_KEY, true);
  }

  return item;
}
github DestinyItemManager / DIM / src / app / storage / indexed-db-storage.js View on Github external
get: function() {
      return idbKeyval.get('DIM-data').then((value) => {
        // Fall back to local storage as a migration aid
        if (!value || _.isEmpty(value)) {
          return JSON.parse(localStorage.getItem('DIM'));
        }
        return value;
      });
    },
github DestinyItemManager / DIM / src / scripts / vendors / vendor.service.js View on Github external
function deleteCachedVendors() {
    // Everything's in one table, so we can't just clear
    idbKeyval.keys().then((keys) => {
      keys.forEach((key) => {
        if (key.startsWith('vendor')) {
          idbKeyval.delete(key);
        }
      });
    });
  }
github datavized / twotone / src / engine / speech-voices.js View on Github external
.then(response => {
			if (response.error) {
				throw new Error(response.error.message);
			}

			const voices = new Map();
			response.voices.forEach(voice => {
				voice.isWaveNet = voice.name.indexOf('Wavenet') >= 0;
				voice.gender = capitalize(voice.ssmlGender);
				voices.set(voice.name, voice);
			});

			// store voices in indexedDB
			return idbKeyval.keys(voicesCacheDB)
				.then(oldKeys => {
					const promises = Array.from(voices.values())
						.map(voice => idbKeyval.set(voice.name, voice, voicesCacheDB));

					// remove any deleted voices
					oldKeys.forEach(key => {
						if (!voices.has(key)) {
							promises.push(idbKeyval.del(key, voicesCacheDB));
						}
					});

					return Promise.all(promises).then(() => voices);
				});
		})
		.catch(err => {

idb-keyval

A super-simple-small keyval store built on top of IndexedDB

Apache-2.0
Latest version published 1 year ago

Package Health Score

73 / 100
Full package analysis