DocIterator.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. module.exports = class DocIterator {
  2. constructor(packs, getPackByIdFn) {
  3. this.getPackByIdFn = getPackByIdFn
  4. // sort packs in descending order by version (i.e. most recent first)
  5. const byVersion = (a, b) => b.v - a.v
  6. this.packs = packs.slice().sort(byVersion)
  7. this.queue = []
  8. }
  9. next(callback) {
  10. const update = this.queue.shift()
  11. if (update) {
  12. return callback(null, update)
  13. }
  14. if (!this.packs.length) {
  15. this._done = true
  16. return callback(null)
  17. }
  18. const nextPack = this.packs[0]
  19. this.getPackByIdFn(
  20. nextPack.project_id,
  21. nextPack.doc_id,
  22. nextPack._id,
  23. (err, pack) => {
  24. if (err != null) {
  25. return callback(err)
  26. }
  27. this.packs.shift() // have now retrieved this pack, remove it
  28. for (const op of pack.pack.reverse()) {
  29. op.doc_id = nextPack.doc_id
  30. op.project_id = nextPack.project_id
  31. this.queue.push(op)
  32. }
  33. return this.next(callback)
  34. }
  35. )
  36. }
  37. done() {
  38. return this._done
  39. }
  40. }