dispatch/client/js/middleware/socket.js

37 lines
870 B
JavaScript
Raw Normal View History

import debounce from 'lodash/debounce';
const debounceKey = action => {
2018-03-25 00:34:41 +00:00
const { key } = action.socket.debounce;
if (key) {
return `${action.type} ${key}`;
}
return action.type;
};
2015-12-28 23:34:32 +00:00
export default function createSocketMiddleware(socket) {
return () => next => {
const debounced = {};
return action => {
if (action.socket) {
if (action.socket.debounce) {
const key = debounceKey(action);
if (!debounced[key]) {
debounced[key] = debounce((type, data) => {
socket.send(type, data);
debounced[key] = undefined;
}, action.socket.debounce.delay);
}
debounced[key](action.socket.type, action.socket.data);
} else {
socket.send(action.socket.type, action.socket.data);
}
}
2015-12-28 23:34:32 +00:00
return next(action);
};
2015-12-28 23:34:32 +00:00
};
}