summaryrefslogtreecommitdiffstats
path: root/devtools/client/shared/async-store-helper.js
blob: b24d56e62914071cd4d2e1874b6db16c9b3d09f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */

"use strict";

const asyncStorage = require("resource://devtools/shared/async-storage.js");

/*
 * asyncStoreHelper wraps asyncStorage so that it is easy to define project
 * specific properties. It is similar to PrefsHelper.
 *
 * e.g.
 *   const asyncStore = asyncStoreHelper("r", {a: "_a"})
 *   asyncStore.a         // => asyncStorage.getItem("r._a")
 *   asyncStore.a = 2     // => asyncStorage.setItem("r._a", 2)
 */
function asyncStoreHelper(root, mappings) {
  let store = {};

  function getMappingKey(key) {
    return Array.isArray(mappings[key]) ? mappings[key][0] : mappings[key];
  }

  function getMappingDefaultValue(key) {
    return Array.isArray(mappings[key]) ? mappings[key][1] : null;
  }

  Object.keys(mappings).map(key =>
    Object.defineProperty(store, key, {
      async get() {
        const value = await asyncStorage.getItem(
          `${root}.${getMappingKey(key)}`
        );
        return value || getMappingDefaultValue(key);
      },
      set(value) {
        asyncStorage.setItem(`${root}.${getMappingKey(key)}`, value);
      },
    })
  );

  store = new Proxy(store, {
    set(target, property) {
      if (!mappings.hasOwnProperty(property)) {
        throw new Error(`AsyncStore: ${property} is not defined in mappings`);
      }

      Reflect.set(...arguments);
      return true;
    },
  });

  return store;
}

module.exports = asyncStoreHelper;