all files / couch/couch/changes/feed/ feed.js

88.46% Statements 23/26
70% Branches 7/10
87.5% Functions 7/8
88.46% Lines 23/26
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                                                      21× 20×   21×           21× 21× 21× 21×       19×       41× 41× 41×       33×     33× 33×     33× 33× 22×   11×       30×       28×       33×                  
import Ember from 'ember';
import composeURL from '../../../util/compose-url';
 
const {
  merge
} = Ember;
 
/*
 
  let feed = new Feed(`http://127.0.0.1:5984/thing/_changes?feed=longpoll&include_docs=true&since=now`);
 
  feed.delegate = {
    onData(f, data) {
      ...
    }
    onError(f, err) {
      ...
    }
  }
 
  feed.start()
 
  ...
 
  feed.stop();
 
*/
 
const defaults = opts => {
  if(!opts.reconnect) {
    opts.reconnect = 3000;
  }
  return opts;
}
 
export default class Feed {
 
  constructor(opts, context) {
    this.opts = defaults(opts);
    this.context = context;
    this.delegate = null;
    this.started = false;
  }
 
  request() {
    return this.context.request(...arguments);
  }
 
  get url() {
    let { url, qs } = this.opts;
    qs = merge(this.qs || {}, qs);
    return composeURL(url, qs);
  }
 
  notify(name, ...args) {
    Iif(!this.started) {
      return;
    }
    let delegate = this.delegate;
    Iif(!delegate) {
      return;
    }
    let fn = delegate[name];
    if(!fn) {
      return;
    }
    fn.call(delegate, this, ...args);
  }
 
  start() {
    this.started = true;
  }
 
  stop() {
    this.started = false;
  }
 
  onError(err) {
    this.notify('onError', err);
  }
 
  onData(json) {
    this.notify('onData', json);
  }
 
}