tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

async-store-helper.js (1604B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
      4 
      5 "use strict";
      6 
      7 const asyncStorage = require("resource://devtools/shared/async-storage.js");
      8 
      9 /*
     10 * asyncStoreHelper wraps asyncStorage so that it is easy to define project
     11 * specific properties. It is similar to PrefsHelper.
     12 *
     13 * e.g.
     14 *   const asyncStore = asyncStoreHelper("r", {a: "_a"})
     15 *   asyncStore.a         // => asyncStorage.getItem("r._a")
     16 *   asyncStore.a = 2     // => asyncStorage.setItem("r._a", 2)
     17 */
     18 function asyncStoreHelper(root, mappings) {
     19  let store = {};
     20 
     21  function getMappingKey(key) {
     22    return Array.isArray(mappings[key]) ? mappings[key][0] : mappings[key];
     23  }
     24 
     25  function getMappingDefaultValue(key) {
     26    return Array.isArray(mappings[key]) ? mappings[key][1] : null;
     27  }
     28 
     29  Object.keys(mappings).map(key =>
     30    Object.defineProperty(store, key, {
     31      async get() {
     32        const value = await asyncStorage.getItem(
     33          `${root}.${getMappingKey(key)}`
     34        );
     35        return value || getMappingDefaultValue(key);
     36      },
     37      set(value) {
     38        asyncStorage.setItem(`${root}.${getMappingKey(key)}`, value);
     39      },
     40    })
     41  );
     42 
     43  store = new Proxy(store, {
     44    set(target, property) {
     45      if (!mappings.hasOwnProperty(property)) {
     46        throw new Error(`AsyncStore: ${property} is not defined in mappings`);
     47      }
     48 
     49      Reflect.set(...arguments);
     50      return true;
     51    },
     52  });
     53 
     54  return store;
     55 }
     56 
     57 module.exports = asyncStoreHelper;