Code coverage report for src/turbobreaker.js

Statements: 100% (44 / 44)      Branches: 100% (20 / 20)      Functions: 100% (11 / 11)      Lines: 100% (27 / 27)      Ignored: 1 branch     

All files » src/ » turbobreaker.js
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        1   1 1   1 1 7 5 5   7 7       3 5         7       7 6 6   5   5           5   5 5     5     1 1     7 7    
import http from 'http';
import {parse} from 'url';
import 'es6-collections';
 
const HYSTRIX_STREAM_PATH = '/hystrix.stream';
 
const clients = new Set();
const noop = () => {};
 
export class TurboBreaker {
  constructor(config = {}, callback = noop) {
    if (typeof config === 'function') {
      callback = config;
      config = {};
    }
    this.config = config;
    this.server = this.createServer(callback);
  }
 
  command(data) {
    clients.forEach(res => {
      res.write("data: " + JSON.stringify(data) + "\n\n");
    });
  }
 
  stop() {
    this.server.close();
  }
 
  createServer(callback) {
    const server = http.createServer((req, res) => {
      const path = parse(req.url).path;
      if (path === HYSTRIX_STREAM_PATH) {
        // Stop the connection from timing out:
        req.setTimeout(0);
        // Get the client to understand us:
        res.writeHead(200, {
          'Content-Type': 'text/event-stream',
          'Cache-Control': 'no-cache',
          'Connection': 'keep-alive'
        });
 
        res.write("\n");
 
        req.on('close', () => {
          clients.delete(res);
        });
 
        clients.add(res);
      } else {
        // Reject the request:
        res.writeHead(404);
        res.end();
      }
    });
    server.listen(this.config.port || 8080, callback);
    return server;
  }
}