Files
ndm-web-client/src/composables/query/station/use-station-list-query.ts

70 lines
2.4 KiB
TypeScript

import type { Station } from '@/apis/domains';
import { batchVerify } from '@/apis/requests';
import { STATION_LIST_QUERY_KEY } from '@/constants';
import { useQueryControlStore } from '@/stores/query-control';
import { useStationStore } from '@/stores/station';
import { getAppEnvConfig } from '@/utils/env';
import { isCancelledError, useMutation, useQuery } from '@tanstack/vue-query';
import axios from 'axios';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { computed } from 'vue';
export function useStationListQuery() {
const queryControlStore = useQueryControlStore();
const { pollingEnabled } = storeToRefs(queryControlStore);
const { mutateAsync: getStationList } = useStationListMutation();
return useQuery({
queryKey: [STATION_LIST_QUERY_KEY],
enabled: computed(() => pollingEnabled.value),
refetchInterval: getAppEnvConfig().requestInterval * 1000,
staleTime: getAppEnvConfig().requestInterval * 1000,
queryFn: async ({ signal }) => {
console.time('useStationListQuery');
await getStationList({ signal });
console.timeEnd('useStationListQuery');
queryControlStore.updateDeviceQueryStamp();
queryControlStore.updateAlarmQueryStamp();
return null;
},
});
}
interface StationListMutationParams {
signal?: AbortSignal;
}
function useStationListMutation() {
const stationStore = useStationStore();
const { stationList } = storeToRefs(stationStore);
return useMutation<Station[], Error, StationListMutationParams>({
mutationFn: async ({ signal }) => {
const { data: ndmStationList } = await axios.get<{ code: string; name: string }[]>(`/minio/ndm/ndm-stations.json?_t=${dayjs().unix()}`, { signal });
const stations = ndmStationList.map<Station>((station) => ({
code: station.code ?? '',
name: station.name ?? '',
online: false,
}));
const verifyList = await batchVerify(signal);
return stations.map((station) => {
return {
...station,
online: !!verifyList.find((stn) => stn.stationCode === station.code)?.onlineState,
};
});
},
onSuccess: (stations) => {
const isSame = JSON.stringify(stationList.value) === JSON.stringify(stations);
if (!isSame) {
stationList.value.splice(0, stationList.value.length, ...stations);
}
},
onError: (error) => {
if (!isCancelledError(error)) {
throw error;
}
},
});
}