summaryrefslogtreecommitdiff
path: root/src/Store/store.ts
blob: b8f41697eec521018b8570b0610ca6479b662342 (plain) (blame)
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
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { createReducer } from 'redux-su';
import { composeWithDevTools } from 'redux-devtools-extension';
import { Portal, Link, Field } from '../Api/types';

const reducers = {
    'auth': createReducer({
        'authSet': (store: any, action: { v: string, csrf: string, user: any }) => ({ v: action.v, csrf: action.csrf, user: action.user, loading: false }),
        'authLoad': (store: any, action: { loading: boolean }) => ({ ...store, loading: action.loading })
    }, { v: "", csrf: "", user: null, loading: false }),
    'entities': createReducer({
        'portalSet': (store: any, action: { guid: string, portal: Portal }) =>
            ({ ...store, portals: { ...store.portals, [action.guid]: { ...action.portal } } }),
        'linkSet': (store: any, action: { guid: string, link: Link }) =>
            ({ ...store, links: { ...store.links, [action.guid]: action.link } }),
        'fieldSet': (store: any, action: { guid: string, field: Field }) =>
            ({ ...store, fields: { ...store.fields, [action.guid]: action.field } }),
        'portalsSet': (store: any, action: { portals: Portal }) => {
            const portals = store.portals
            Object.keys(action.portals).forEach(guid => {
                const portal: Portal = portals[guid]
                const newPortal: Portal = action.portals[guid]
                if (!portal) {
                    portals[guid] = newPortal
                    return
                }
                portals[guid] = extend(portal, newPortal)
            })
            return { ...store, portals }
        },
        'linksSet': (store: any, action: { links: { [guid: string]: Link } }) =>
            ({ ...store, links: { ...store.links, ...action.links } }),
        'fieldsSet': (store: any, action: { fields: { [guid: string]: Field } }) =>
            ({ ...store, fields: { ...store.fields, ...action.fields } }),
        'setLoad': (store: any, action: { queue: string[][] }) =>
            ({ ...store, loadQueue: [...action.queue] }),

    }, { portals: {}, fields: {}, links: {}, loadQueue: [] })
}

function extend(obj: any, src: any) {
    for (var key in src) {
        if (src.hasOwnProperty(key) && !!src[key]) {
            obj[key] = src[key];
        }
    }
    return obj;
}

const store = createStore(
    combineReducers(reducers),
    composeWithDevTools(applyMiddleware(thunk))
)
export default store