Skip to content
Snippets Groups Projects
mne.routine.ts 1.69 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { api, NetworkElementServiceGetApiArg } from "@api/api";
    
    import { Device, setSelectedDevice, setSelectedMne } from "@component/devices/reducer/device.reducer";
    
    import { createAsyncThunk } from "@reduxjs/toolkit";
    
    import { addRoutine, CATEGORIES } from "@shared/reducer/routine.reducer";
    
    import { RootState } from "src/stores";
    
    import { startListening } from "../../../stores/middleware/listener.middleware";
    
    
    export const FETCH_MNE_ACTION = 'subscription/device/fetchSelectedMNE';
    
    
    
    // fetch mne if selected device is set
    startListening({
        predicate: (action) => setSelectedDevice.match(action) && !!action.payload,
        effect: async (action, listenerApi) => {
    
            listenerApi.dispatch(addRoutine({thunk: fetchSelectedMneThunk, category: CATEGORIES.TAB, payload: action.payload}));
    
        },
    })
    
    
    const FETCH_MNE_INTERVAL = 5000; // in ms
    export const fetchSelectedMneThunk = createAsyncThunk(FETCH_MNE_ACTION, async (device: Device, thunkApi) => {
        const { user } = thunkApi.getState() as RootState;
    
        const payload: NetworkElementServiceGetApiArg = {
            pid: Object.keys(user?.user.roles)[0],
            timestamp: new Date().getTime().toString(),
            mneid: device.id,
        }
    
        const subscription = thunkApi.dispatch(api.endpoints.networkElementServiceGet.initiate(payload, {
            subscriptionOptions: {
                pollingInterval: FETCH_MNE_INTERVAL,
                skipPollingIfUnfocused: true,
            }
        }));
    
        return {...subscription};
    });
    
    // save fetched mne
    startListening({
        predicate: (action) => api.endpoints.networkElementServiceGet.matchFulfilled(action),
        effect: async (action, listenerApi) => {
            listenerApi.dispatch(setSelectedMne(action.payload.mne));
        },
    })