Skip to content
Snippets Groups Projects
mne.subscription.ts 1.7 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { api, NetworkElementServiceGetApiArg } from "@api/api";
    import { Device, setSelectedDevice, setSelectedMne } from "@reducer/device.reducer";
    import { CATEGORIES, triggerSubscription } from "@reducer/subscription.reducer";
    import { createAsyncThunk } from "@reduxjs/toolkit";
    import { RootState } from "src/stores";
    import { THUNK_TYPE } from ".";
    import { startListening } from "../../../src/stores/middleware/listener.middleware";
    import { FETCH_MNE_ACTION } from "./action.subscription";
    
    // fetch mne if selected device is set
    startListening({
        predicate: (action) => setSelectedDevice.match(action) && !!action.payload,
        effect: async (action, listenerApi) => {
            listenerApi.dispatch(triggerSubscription({category: CATEGORIES.TAB, thunkType: THUNK_TYPE.MNE, 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));
        },
    })