all files / couch/couch/changes/feed/ event-source.js

87.1% Statements 27/31
50% Branches 2/4
70% Functions 7/10
87.1% Lines 27/31
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                    12×       13× 13× 13×                 22×             22× 22× 88×   22× 22×       21× 21× 21× 84×   21× 21× 21×       14× 14×                   14× 14× 14× 14×                              
import Ember from 'ember';
import Feed from './feed';
import Error from '../../../util/error';
 
const {
  run: { later, cancel }
} = Ember;
 
export default class EventSourceFeed extends Feed {
 
  static isSupported() {
    return typeof(EventSource) !== "undefined";
  }
 
  constructor(opts, context) {
    super(opts, context);
    this.source = null;
    this.bound = {
      open: this.onOpen.bind(this),
      error: this.onError.bind(this),
      message: this.onMessage.bind(this),
      heartbeat: this.onHeartbeat.bind(this)
    };
  }
 
  get qs() {
    return {
      feed: 'eventsource'
    };
  }
 
  start() {
    /* global EventSource */
    let source = new EventSource(this.url, { withCredentials: true });
    for(let key in this.bound) {
      source.addEventListener(key, this.bound[key], false);
    }
    this.source = source;
    super.start();
  }
 
  stop() {
    let source = this.source;
    source.close();
    for(let key in this.bound) {
      source.removeEventListener(key, this.bound[key], false);
    }
    this.source = null;
    cancel(this._start);
    super.stop();
  }
 
  enqueueRestart() {
    cancel(this._start);
    this._start = later(() => {
      Iif(!this.started) {
        return;
      }
      this.stop();
      this.start();
    }, this.opts.reconnect);
  }
 
  onOpen() {
  }
 
  onError(e) {
    let readyState = e.target.readyState;
    super.onError(new Error({ error: 'event source', reason: 'unknown', readyState }));
    Eif(readyState !== e.target.OPEN) {
      this.enqueueRestart();
    }
  }
 
  onHeartbeat() {
  }
 
  onMessage(message) {
    let data = message.data;
    let json = JSON.parse(data);
    this.onData(json);
  }
 
}