joyent-portal/spikes/graphs-matrix/chartjs/client/actions.js

64 lines
1.2 KiB
JavaScript
Raw Normal View History

2016-11-09 15:58:10 +02:00
const takeRight = require('lodash.takeright');
const actions = {
'UPDATE_STATS': (state, action) => {
const data = (state[action.subscription] || []).concat([action.payload]);
return {
...state,
2016-11-09 17:00:30 +02:00
[action.subscription]: takeRight(data, state.windowSize)
2016-11-09 15:58:10 +02:00
};
}
};
module.exports = (state, action) => {
return !actions[action.type] ? state : actions[action.type](state, action);
};
module.exports.subscribe = (id) => (dispatch, getState) => {
const {
ws
} = getState();
const p = new Promise((resolve, reject) => {
ws.subscribe(`/stats/${id}`, (update, flag) => {
dispatch({
type: 'UPDATE_STATS',
payload: update,
subscription: id
});
}, (err) => {
if (err) {
return reject(err);
}
resolve();
});
});
return dispatch({
action: 'SUBSCRIBE',
payload: p
});
};
module.exports.unsubscribe = (id) => (dispatch, getState) => {
const {
ws
} = getState();
const p = new Promise((resolve, reject) => {
ws.unsubscribe(`/stats/${id}`, null, (err) => {
if (err) {
return reject(err);
}
resolve();
});
});
return dispatch({
action: 'UNSUBSCRIBE',
payload: p
});
};