-
Notifications
You must be signed in to change notification settings - Fork 0
/
serverRedux.js
80 lines (67 loc) · 2.06 KB
/
serverRedux.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
var redux = require('redux');
var db = require('./models');
var state = (state = {}, action) => {
return Object.assign({}, state, action.payload);
};
var store = redux.createStore(state);
exports.getState = () => {
return store.getState();
};
exports.subscribe = (cb) => {
let prevState;
store.subscribe(() => {
const state = store.getState();
if (prevState !== state) {
prevState = state;
cb(state)
}
})
};
function isChanged(newProps, prevState) {
for (let item in newProps) {
if (prevState === undefined)
return true
if (newProps[item] !== prevState[item.toString()]){
return true
}
}
return false
}
exports.subscribeDeviceChanges = (cb) => {
let prevState = {};
store.subscribe(() => {
db.device.findAll().then(devices => {
devices.forEach(device => {
if (device.propFunction !== ''){
let func = new Function('state', device.propFunction);
const state = store.getState();
const newProps = func(state);
if (isChanged(newProps, prevState[(device.id).toString()], device)) {
cb(device.id, newProps)
}
prevState[device.id] = newProps;
}
})
})
})
};
exports.dispatchActionFromDevice = (data) => {
return db.rule.findAll({where: {sourceID: data.id, sourceType: 'device'}}).then((rules) => {
console.log("this is rules", rules);
rules.forEach(rule => {
let func = new Function('device', 'payload', 'state', rule.func);
let result = func(data.device, data.payload, store.getState());
store.dispatch({type: '', payload: result})
})
})
// store.dispatch({type: '', payload: data.payload})
};
exports.dispatchActions = (id, element, event, payload) => {
return db.rule.findAll({where: {sourceID: id, sourceType: 'control'} }).then((rules) => {
rules.forEach(item => {
let func = new Function('item', 'event', 'payload', 'state', item.func);
let result = func(element, event, payload, store.getState());
store.dispatch({type: '',payload:result});
})
})
};