aboutsummaryrefslogtreecommitdiffstats
path: root/web/src/js/ducks/settings.js
blob: 6de1c2afb2e8d6e41ce2d5c09fdccbb37191baf7 (plain)
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
import { addLogEntry } from './eventLog'

export const WS_MSG_TYPE = 'settings'
export const WS_MSG_CMD_UPDATE = 'update'

export const BEGIN_FETCH = 'SETTINGS_BEGIN_FETCH'
export const FETCHED = 'SETTINGS_FETCHED'
export const RECV_WS_MSG = 'SETTINGS_RECV_WS_MSG'

const defaultState = { settings: {}, pendings: null }

export default function reduce(state = defaultState, action) {
    switch (action.type) {

        case BEGIN_FETCH:
            return { ...state, pendings: [] }

        case FETCHED:
            const pendings = state.pendings || []
            return { ...state, pendings: null, settings: pendings.reduce(reduceData, action.data) }

        case RECV_WS_MSG:
            if (state.pendings) {
                return { ...state, pendings: state.pendings.concat(action) }
            }
            return { ...state, settings: reduceData(state.settings, action) }

        default:
            return state
    }
}

function reduceData(data, action) {
    switch (action.cmd) {

        case WS_MSG_CMD_UPDATE:
            return { ...data, ...action.data }

        default:
            return data
    }
}

export function fetch() {
    return dispatch => {
        dispatch({ type: BEGIN_FETCH })
        return $.getJSON('/settings')
            .done(msg => dispatch(handleFetchResponse(msg.data)))
            .fail(error => dispatch(handleFetchError(error)));
    }
}

export function handleWsMsg(msg) {
    return { type: RECV_WS_MSG, cmd: msg.cmd, data: msg.data }
}

export function handleFetchResponse(data) {
    return { type: FETCHED, data }
}

export function handleFetchError(error) {
    // @todo let eventLog subscribe to SettingsActions.FETCH_ERROR
    return addLogEntry(error.stack || error.message || error)
}