useMessageLoop.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { effectScope, onScopeDispose, watch } from 'vue'
  2. import { useIntervalFn } from '@vueuse/core'
  3. import uesFetch from '@/hooks/useFetch'
  4. import useMainStore from '@/store/main'
  5. import type { EffectScope, ShallowRef } from 'vue'
  6. import type { ExtractApiResponse } from 'api-type'
  7. const useMessageLoop = () => {
  8. const mainStore = useMainStore()
  9. const { fetch: getUnReadMessage, result: unReadMessage } = uesFetch('getUnReadMessage')
  10. watch(
  11. () => mainStore?.myUserInfo?.role,
  12. () => {
  13. if (mainStore?.myUserInfo?.role && mainStore?.myUserInfo?.role !== 'ADMIN') {
  14. getUnReadMessage()
  15. useIntervalFn(getUnReadMessage, 30 * 1000)
  16. }
  17. },
  18. {
  19. immediate: true,
  20. }
  21. )
  22. return unReadMessage
  23. }
  24. function createSharedComposable(composable: typeof useMessageLoop) {
  25. let subscribers = 0
  26. let state: ShallowRef<ExtractApiResponse<'getUnReadMessage'>> | null | undefined
  27. let scope: EffectScope | null
  28. const dispose = () => {
  29. if (scope && --subscribers <= 0) {
  30. scope.stop()
  31. state = scope = null
  32. }
  33. }
  34. return () => {
  35. subscribers++
  36. if (!state) {
  37. scope = effectScope(true)
  38. state = scope.run<ShallowRef<ExtractApiResponse<'getUnReadMessage'>>>(composable)
  39. }
  40. onScopeDispose(dispose)
  41. return state
  42. }
  43. }
  44. export default createSharedComposable(useMessageLoop)