All files / src/commons base-replicator.js

100% Statements 35/35
90% Branches 18/20
100% Functions 4/4
100% Lines 33/33
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  1x 1x   1x 1x     72x 72x       72x 72x 72x   72x       20x     65x 65x   65x   65x 65x   65x 65x         12x       4x       7x         657x         3x 3x   3x 56x 56x   56x 58x 58x   58x 58x     56x        
 
import snapshot from 'feathers-offline-snapshot';
import { genUuid } from './utils';
 
import makeDebug from 'debug';
const debug = makeDebug('base-replicator');
 
export default class BaseReplicator {
  constructor (service, options = {}) {
    debug('constructor entered');
 
    // Higher order class defines: this.engine, this.store, this.changeSort, this.on
 
    this._service = service;
    this._query = options.query || {};
    this._publication = options.publication;
 
    this.genShortUuid = true;
  }
 
  get connected () {
    return this.engine.listening;
  }
 
  connect () {
    this.engine.removeListeners();
 
    return snapshot(this._service, this._query)
      .then(records => {
        records = this._publication ? records.filter(this._publication) : records;
        records = this.engine.sorter ? records.sort(this.engine.sorter) : records;
 
        this.engine.snapshot(records);
        this.engine.addListeners();
      });
  }
 
  disconnect () {
    this.engine.removeListeners();
  }
 
  useShortUuid (ifShortUuid) {
    this.genShortUuid = !!ifShortUuid;
  }
 
  getUuid () {
    return genUuid(this.genShortUuid);
  }
 
  // array.sort(Realtime.sort('fieldName'));
  static sort (prop) {
    return (a, b) => a[prop] > b[prop] ? 1 : (a[prop] < b[prop] ? -1 : 0);
  }
 
  // array.sort(Realtime.multiSort({ field1: 1, field2: -1 }))
  static multiSort (order) {
    const props = Object.keys(order);
    const len = props.length;
 
    return (a, b) => {
      let result = 0;
      let i = 0;
 
      while (result === 0 && i < len) {
        const prop = props[i];
        const sense = order[prop];
 
        result = a[prop] > b[prop] ? 1 * sense : (a[prop] < b[prop] ? -1 * sense : 0);
        i++;
      }
 
      return result;
    };
  }
}