2017-06-12 04:18:32 +00:00
|
|
|
import debounce from 'lodash/debounce';
|
|
|
|
|
|
|
|
const debounceKey = action => {
|
2018-03-25 00:34:41 +00:00
|
|
|
const { key } = action.socket.debounce;
|
2017-06-12 04:18:32 +00:00
|
|
|
if (key) {
|
|
|
|
return `${action.type} ${key}`;
|
|
|
|
}
|
|
|
|
return action.type;
|
|
|
|
};
|
|
|
|
|
2015-12-28 23:34:32 +00:00
|
|
|
export default function createSocketMiddleware(socket) {
|
2017-06-12 04:18:32 +00:00
|
|
|
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
|
|
|
|
2017-06-12 04:18:32 +00:00
|
|
|
return next(action);
|
|
|
|
};
|
2015-12-28 23:34:32 +00:00
|
|
|
};
|
|
|
|
}
|