Skip to content

Commit

Permalink
Support webpack-hot-middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
blainekasten committed Dec 12, 2019
1 parent 70a3f55 commit 986e7e3
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/runtime/createSocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
/* global __resourceQuery, __webpack_dev_server_client__ */

const url = require('url');
const tryLoadingWHMEventSource = require('./loadWHMEventSource');

// This adds support for custom WDS socket transportModes
// In the future, we should add support for custom clients to better support WDM
Expand All @@ -17,6 +18,8 @@ if (typeof __webpack_dev_server_client__ !== 'undefined') {
* @param {function(*): void} messageHandler A handler to consume Webpack compilation messages.
*/
function createSocket(messageHandler) {
tryLoadingWHMEventSource();

const connection = new SocketClient(
// TODO: Dynamically generate this to handle resourceQuery
// TODO: Use resourceQuery to fix servers under proxies
Expand All @@ -29,11 +32,9 @@ function createSocket(messageHandler) {
pathname: '/sockjs-node',
})
);

connection.onClose(function onSocketClose() {
// TODO: Should we reconnect?
});

connection.onMessage(function onSocketMessage(data) {
const message = JSON.parse(data);
messageHandler(message);
Expand Down
37 changes: 37 additions & 0 deletions src/runtime/loadWHMEventSource.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* If the consumers setup is to use webpack-hot-middleware with a custom express server
* we want to bind onto the EventSource for our updates.
*
* The EventSource is not attached immediately, so we have a timeout + retry mechanism.
* This is also a safe approach for consumers who are not using webpack-hot-middleware. It'll be a noop after 3s.
*/
const MAX_RETRIES = 3;
let retries = 0;

function tryLoadingWHMEventSource() {
setTimeout(() => {
if (!window.__whmEventSourceWrapper) {
if (retries >= MAX_RETRIES) return;
retries++;
tryLoadingWHMEventSource();
return;
}

const eventSource = Object.values(window.__whmEventSourceWrapper)[0];
eventSource.addMessageListener(event => {
try {
const message = JSON.parse(event.data);
messageHandler(message);
} catch (e) {
// heartbeat
if (event.data === '💓') {
return;
}

console.error(e);
}
});
}, 1000);
}

module.exports = tryLoadingWHMEventSource;

0 comments on commit 986e7e3

Please sign in to comment.