All files inStorageCache.js

100% Statements 46/46
100% Branches 34/34
100% Functions 14/14
100% Lines 46/46
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198    1x         1x 59x                   7x                                                                   89x     27x   27x 1x     26x 1x     25x             25x                       10x 9x                     10x   10x 9x     10x               34x 1x         33x 1x         32x 1x         31x 1x         30x 1x         29x 29x       1x         1x       176x 54x         176x       54x 44x           54x       2x 1x     2x       2x 2x       26x   26x 2x            
import { InMemoryCache } from 'apollo-cache-inmemory'
 
const defaults = {
  normalize: JSON.stringify,
  denormalize: JSON.parse
}
 
const validStorage = storage =>
  Boolean(
    storage &&
      storage.getItem &&
      storage.setItem &&
      storage.removeItem &&
      storage.clear
  )
 
class InStorageCacheError extends Error {
  constructor (message, ...args) {
    super(`[InStorageCacheError] ${message}`, ...args)
  }
}
 
class InStorageCache extends InMemoryCache {
  /**
   * @property {(Object|Function)} storage - The Storage to use.
   *
   * @see https://www.w3.org/TR/webstorage/#storage
   */
  storage
 
  /**
   * @property {Function} [normalize] - Normalization callback. Executed
   * prior to storing a resource.
   */
  normalize
 
  /**
   * @property {Function} [denormalize] - Denormalization callback. Executed
   * after retrieving a cached resource from the storage.
   */
  denormalize
 
  /**
   * @property {Function} [shouldPersist] - Callback to determine if a given
   * data should be cached.
   */
  shouldPersist
 
  constructor ({
    storage,
    normalize = DepTrackingStorageCache.normalize,
    denormalize = DepTrackingStorageCache.denormalize,
    shouldPersist = () => true,
    ...config
  } = {}) {
    super(config)
 
    if (!storage) {
      throw new InStorageCacheError('You must provide a storage to use')
    }
 
    if (!validStorage(storage)) {
      throw new InStorageCacheError('You must provide a valid storage to use')
    }
 
    this.persistence = {
      storage,
      normalize,
      denormalize,
      shouldPersist
    }
 
    this.data = new DepTrackingStorageCache(null, this.persistence)
  }
}
 
class DepTrackingStorageCache {
  /**
   * Iterates each key of the storage and execute the callback on it.
   *
   * @param {Object} storage The storage instance.
   * @param {Function} callback The iteration callback.
   */
  static iterate (storage, callback) {
    for (let i = 0; i < storage.length; ++i) {
      callback(storage.key(i))
    }
  }
 
  /**
   * Creates a plain object from all the storage's persisted data.
   *
   * @param {Object} storage The storage instance.
   * @param {Function} denormalize Method of denormalizing the retrieved resource.
   */
  static toObject (storage, denormalize = defaults.denormalize) {
    const object = {}
 
    DepTrackingStorageCache.iterate(storage, key => {
      object[key] = denormalize(storage.getItem(key))
    })
 
    return object
  }
 
  static normalize = defaults.normalize
 
  static denormalize = defaults.denormalize
 
  constructor (data = {}, persistence = {}) {
    if (!persistence.storage) {
      throw new InStorageCacheError(
        'You must provide a persistence.storage to use'
      )
    }
 
    if (!validStorage(persistence.storage)) {
      throw new InStorageCacheError(
        'You must provide a valid persistence.storage to use'
      )
    }
 
    if (typeof persistence.normalize !== 'function') {
      throw new InStorageCacheError(
        'You must provide a persistence.normalize function'
      )
    }
 
    if (typeof persistence.denormalize !== 'function') {
      throw new InStorageCacheError(
        'You must provide a persistence.denormalize function'
      )
    }
 
    if (typeof persistence.shouldPersist !== 'function') {
      throw new InStorageCacheError(
        'You must provide a persistence.shouldPersist function'
      )
    }
 
    this.persistence = persistence
    this.data = { ...data }
  }
 
  toObject () {
    const persisted = DepTrackingStorageCache.toObject(
      this.persistence.storage,
      this.persistence.denormalize
    )
 
    return { ...persisted, ...this.data }
  }
 
  get (dataId) {
    if (!this.data[dataId] && this.persistence.shouldPersist('get', dataId)) {
      this.data[dataId] = this.persistence.denormalize(
        this.persistence.storage.getItem(dataId)
      )
    }
 
    return this.data[dataId]
  }
 
  set (dataId, value) {
    if (this.persistence.shouldPersist('set', dataId, value)) {
      this.persistence.storage.setItem(
        dataId,
        this.persistence.normalize(value)
      )
    }
 
    this.data[dataId] = value
  }
 
  delete (dataId) {
    if (this.persistence.shouldPersist('delete', dataId)) {
      this.persistence.storage.removeItem(dataId)
    }
 
    this.data[dataId] = undefined
  }
 
  clear () {
    this.persistence.storage.clear()
    this.data = {}
  }
 
  replace (newData) {
    this.data = {}
 
    for (let dataId in newData) {
      this.set(dataId, newData[dataId])
    }
  }
}
 
export { InStorageCache, DepTrackingStorageCache }