From 09ba503e5d3fc864135ad5d2cd6d80e4c986591f Mon Sep 17 00:00:00 2001 From: Andrew Ray Date: Tue, 28 Jun 2016 14:02:30 -0700 Subject: [PATCH] Adds a subscribeAll() method to the client to handle any events Usage: client.subscribeAll(function(message) { console.log(message.action); }); Only accepts one handler and will overwrite any previously existing handlers. Addresses #111 --- client.js | 8 ++++++++ test/client-test.js | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/client.js b/client.js index 0eda04f..4310f8c 100644 --- a/client.js +++ b/client.js @@ -121,6 +121,7 @@ function createReporter() { var processUpdate = require('./process-update'); var customHandler; +var subscribeAllHandler; function processMessage(obj) { if (obj.action == "building") { if (options.log) console.log("[HMR] bundle rebuilding"); @@ -144,10 +145,17 @@ function processMessage(obj) { } else if (customHandler) { customHandler(obj); } + + if (subscribeAllHandler) { + subscribeAllHandler(obj); + } } if (module) { module.exports = { + subscribeAll: function subscribeAll(handler) { + subscribeAllHandler = handler; + }, subscribe: function subscribe(handler) { customHandler = handler; }, diff --git a/test/client-test.js b/test/client-test.js index eb252ea..106cd9d 100644 --- a/test/client-test.js +++ b/test/client-test.js @@ -39,6 +39,36 @@ describe("client", function() { })); sinon.assert.calledOnce(processUpdate); }); + it("should call subscribeAll handler on default messages", function() { + var spy = sinon.spy(); + client.subscribeAll(spy); + var message = { + action: 'built', + time: 100, + hash: 'deadbeeffeddad', + errors: [], + warnings: [], + modules: [] + }; + + var eventSource = window.EventSource.lastCall.returnValue; + eventSource.onmessage(makeMessage(message)); + + sinon.assert.calledOnce(spy); + sinon.assert.calledWith(spy, message); + }); + it("should call subscribeAll handler on custom messages", function() { + var spy = sinon.spy(); + client.subscribeAll(spy); + + var eventSource = window.EventSource.lastCall.returnValue; + eventSource.onmessage(makeMessage({ + action: 'thingy' + })); + + sinon.assert.calledOnce(spy); + sinon.assert.calledWith(spy, { action: 'thingy' }); + }); it("should call only custom handler on custom messages", function() { var spy = sinon.spy(); client.subscribe(spy); @@ -47,6 +77,9 @@ describe("client", function() { eventSource.onmessage(makeMessage({ custom: 'thingy' })); + eventSource.onmessage(makeMessage({ + action: 'built' + })); sinon.assert.calledOnce(spy); sinon.assert.calledWith(spy, { custom: 'thingy' });