Skip to content
Snippets Groups Projects
device.routine.ts 1.51 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { NetworkElementServiceGetAllFlattenedApiArg, api } from "@api/api";
    
    import { setDevices } from "@component/devices/reducer/device.reducer";
    
    import { createAsyncThunk } from "@reduxjs/toolkit";
    
    import { setUser } from "@shared/reducer/user.reducer";
    
    import { RootState } from "src/stores";
    
    import { startListening } from "../../../stores/middleware/listener.middleware";
    
    
    export const FETCH_DEVICE_ACTION = 'subscription/device/fetchDevices'
    
    
    // continously fetch devices
    const FETCH_DEVICES_INTERVAL = 15000; // in ms
    startListening({
        actionCreator: setUser,
        effect: async (_, listenerApi) => {
            listenerApi.dispatch(fetchDevicesThunk());
        },
    })
    
    
    export const fetchDevicesThunk = createAsyncThunk(FETCH_DEVICE_ACTION, (_, thunkApi) => {
        const { user } = thunkApi.getState() as RootState;
    
        const payload: NetworkElementServiceGetAllFlattenedApiArg = {
            pid: Object.keys(user?.user.roles)[0],
            timestamp: new Date().getTime().toString(),
        }
    
        const subscription = thunkApi.dispatch(api.endpoints.networkElementServiceGetAllFlattened.initiate(payload, {
            subscriptionOptions: {
                pollingInterval: FETCH_DEVICES_INTERVAL,
                skipPollingIfUnfocused: true,
            }
        }));
    
        return subscription;
    });
    
    
    // save fetched devices
    startListening({
        predicate: (action) => api.endpoints.networkElementServiceGetAllFlattened.matchFulfilled(action),
        effect: async (action, listenerApi) => {
            listenerApi.dispatch(setDevices(action.payload.mne));
        },
    })