aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/lib/local-store.js
blob: 2dda0ba1f4703b56758110115c200a5890f603f1 (plain) (blame)
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
58
59
60
61
62
63
// We should not rely on local storage in an extension!
// We should use this instead!
// https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/storage/local

const extension = require('extensionizer')
const log = require('loglevel')

module.exports = class ExtensionStore {
  constructor() {
    this.isSupported = !!(extension.storage.local)
    if (!this.isSupported) {
      log.error('Storage local API not available.')
    }
  }

  async get() {
    if (!this.isSupported) return undefined
    const result = await this._get()
    // extension.storage.local always returns an obj
    // if the object is empty, treat it as undefined
    if (isEmpty(result)) {
      return undefined
    } else {
      return result
    }
  }

  async set(state) {
    return this._set(state)
  }

  _get() {
    const local = extension.storage.local
    return new Promise((resolve, reject) => {
      local.get(null, (result) => {
        const err = extension.runtime.lastError
        if (err) {
          reject(err)
        } else {
          resolve(result)
        }
      })
    })
  }

  _set(obj) {
    const local = extension.storage.local
    return new Promise((resolve, reject) => {
      local.set(obj, () => {
        const err = extension.runtime.lastError
        if (err) {
          reject(err)
        } else {
          resolve()
        }
      })
    })
  }
}

function isEmpty(obj) {
  return Object.keys(obj).length === 0
}