aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/lib/observable/local-storage.js
blob: 6ed3860f6f0f1f14f4a4020da0965608281758a5 (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
const ObservableStore = require('./index')

//
// LocalStorageStore
//
// uses localStorage instead of a cache
//

class LocalStorageStore extends ObservableStore {

  constructor (opts) {
    super()
    delete this._state

    this._opts = opts || {}
    if (!this._opts.storageKey) {
      throw new Error('LocalStorageStore - no "storageKey" specified')
    }
    this._storageKey = this._opts.storageKey
  }

  get() {
    try {
      return JSON.parse(global.localStorage[this._storageKey])
    } catch (err) {
      return undefined
    }
  }

  _put(newState) {
    global.localStorage[this._storageKey] = JSON.stringify(newState)
    this.emit('update', newState)
  }

}

module.exports = LocalStorageStore