public.ts 1.4 KB
Newer Older
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
1
2
import Crop from 'model/Crop';
import {CropService} from 'service/CropService';
3
import {LOAD_CROPS_CACHE_IDLE, RECEIVE_CROPS} from 'crop/constants';
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
4
5
6
7
8
9
10
11
12
import {IReducerAction} from 'model/common.model';
import {log} from 'utilities/debug';


const receiveCrops = (crops: Crop[]): IReducerAction => ({
    type: RECEIVE_CROPS, payload: crops,
});

export const loadCrops = (forceReload: boolean = false) => (dispatch, getState) => {
13
14

    const timeSinceLastFetch = getState().crop.public.lastFetched;
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
15
16
17
18
19

    // perform the API call if the data is older than the allowed limit
    const isDataStale = Date.now() - timeSinceLastFetch > LOAD_CROPS_CACHE_IDLE;

    if (isDataStale || forceReload) {
20
        return CropService.listCrops()
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
21
22
23
24
25
26
27
28
29
30
31
            .then((list) => {
                dispatch(receiveCrops(list));
            })
            .catch((error) => {
                log('Error', error);
            });
    }
};

export const saveCrop = (crop: Crop) => (dispatch, getState) => {

32
    return CropService.saveCrop(crop)
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
33
34
35
36
37
38
39
40
        .then(() => {
            dispatch(loadCrops(true));
        }).catch((error) => {
            log('Save error', error);
        });
};

export const deleteCrop = (crop: Crop) => (dispatch, getState) => {
41
    return CropService.deleteCrop(crop.shortName)
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
42
43
44
45
46
47
48
        .then(() => {
            dispatch(loadCrops(true));
        })
        .catch((error) => {
            log('Error', error);
        });
};