All files inStorageCache.js

100% Statements 11/11
100% Branches 12/12
100% Functions 3/3
100% Lines 11/11
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                        2x                                                                                               89x         35x   35x 1x     34x 1x     33x   33x               33x       189x              
import { InMemoryCache } from 'apollo-cache-inmemory'
 
import { ObjectStorageCache } from './objectStorageCache'
import { addPersistFieldToDocument } from './transform'
 
import {
  InStorageCacheError,
  validStorage,
  normalize,
  denormalize
} from './utils'
 
const defaults = {
  normalize,
  denormalize
}
 
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
 
  /**
   * @property {boolean} [addPersistField] - Whether or not should add a
   * __persist field to all non scalar types in a query.
   */
  addPersistField
 
  /**
   * @property {string} [prefix] - The prefix to use when saving to the
   * provided storage. Useful to diff items from this and other persisting
   * systems that share the same storage.
   */
  prefix
 
  constructor ({
    storage,
    normalize = defaults.normalize,
    denormalize = defaults.denormalize,
    shouldPersist = () => true,
    addPersistField = false,
    prefix = '',
    ...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.addPersistField = addPersistField
 
    this.persistence = {
      storage,
      normalize,
      denormalize,
      shouldPersist,
      prefix
    }
 
    this.data = new ObjectStorageCache(null, this.persistence)
  }
 
  transformDocument (doc) {
    return super.transformDocument(
      this.addPersistField ? addPersistFieldToDocument(doc) : doc
    )
  }
}
 
export { InStorageCache }