all files / collab/ ChangeStore.js

93.33% Statements 28/30
90.48% Branches 19/21
100% Functions 9/9
93.33% Lines 28/30
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            19×                     11×   11×     11× 11× 11× 11×             16×     16× 16× 16×                                           31× 31×       13×       16×   16×          
/*
  Implements Substance ChangeStore API. This is just a dumb store.
  No integrity checks are made, as this is the task of DocumentEngine
*/
class ChangeStore {
  constructor(seed) {
    this._changes = seed || {}
  }
 
  /*
    Gets changes for a given document
 
    @param {String} documentId document id
    @param {Number} sinceVersion since which change (optional)
    @param {Number} toVersion up to and including version (optional)
  */
  getChanges(documentId, sinceVersion, toVersion, cb) {
    if (typeof sinceVersion === 'function') {
      cb = sinceVersion
      sinceVersion = 0
    } else if (typeof toVersion === 'function') {
      cb = toVersion
      toVersion = undefined
    }
    Iif (!(documentId && sinceVersion >= 0 && cb)) {
      throw new Error('Invalid arguments')
    }
    let version = this._getVersion(documentId)
    let changes = this._getChanges(documentId)
    changes = changes.slice(sinceVersion, toVersion)
    cb(null, changes, version)
  }
 
  /*
    Add a change object to the database
  */
  addChange(documentId, change, cb) {
    Iif (!documentId || !change) {
      throw new Error('Invalid arguments')
    }
    this._addChange(documentId, change)
    let newVersion = this._getVersion(documentId)
    cb(null, newVersion)
  }
 
  /*
    Delete changes for a given documentId
  */
  deleteChanges(documentId, cb) {
    var deletedChanges = this._deleteChanges(documentId)
    cb(null, deletedChanges.length)
  }
 
  /*
    Gets the version number for a document
  */
  getVersion(id, cb) {
    cb(null, this._getVersion(id))
  }
 
  // Handy synchronous helpers
  // -------------------------
 
  _deleteChanges(documentId) {
    var changes = this._getChanges(documentId)
    delete this._changes[documentId]
    return changes
  }
 
  _getVersion(documentId) {
    var changes = this._changes[documentId]
    return changes ? changes.length : 0
  }
 
  _getChanges(documentId) {
    return this._changes[documentId] || []
  }
 
  _addChange(documentId, change) {
    if (!this._changes[documentId]) {
      this._changes[documentId] = []
    }
    this._changes[documentId].push(change)
  }
}
 
export default ChangeStore