feat: 增加 useReactionTypes,优化 /reaction-types 接口重复调用

This commit is contained in:
CH-122
2025-08-19 16:52:33 +08:00
parent 27393c15f2
commit a29bf7d860
2 changed files with 60 additions and 24 deletions

View File

@@ -51,6 +51,10 @@ import { computed, onMounted, ref, watch } from 'vue'
import { toast } from '~/main'
import { authState, getToken } from '~/utils/auth'
import { reactionEmojiMap } from '~/utils/reactions'
import { useReactionTypes } from '~/composables/useReactionTypes'
const { reactionTypes, initialize } = useReactionTypes()
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
const emit = defineEmits(['update:modelValue'])
@@ -66,30 +70,6 @@ watch(
)
const reactions = ref(props.modelValue)
const reactionTypes = ref([])
let cachedTypes = null
const fetchTypes = async () => {
if (cachedTypes) return cachedTypes
try {
const token = getToken()
const res = await fetch(`${API_BASE_URL}/api/reaction-types`, {
headers: { Authorization: token ? `Bearer ${token}` : '' },
})
if (res.ok) {
cachedTypes = await res.json()
} else {
cachedTypes = []
}
} catch {
cachedTypes = []
}
return cachedTypes
}
onMounted(async () => {
reactionTypes.value = await fetchTypes()
})
const counts = computed(() => {
const c = {}
@@ -200,6 +180,10 @@ const toggleReaction = async (type) => {
toast.error('操作失败')
}
}
onMounted(async () => {
await initialize()
})
</script>
<style>

View File

@@ -0,0 +1,52 @@
import { ref } from 'vue'
const reactionTypes = ref([])
let isLoading = false
let isInitialized = false
export function useReactionTypes() {
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
const fetchReactionTypes = async () => {
if (isInitialized || isLoading) {
reactionTypes.value = [...(window.reactionTypes || [])]
return reactionTypes.value
}
isLoading = true
try {
const token = getToken()
const res = await fetch(`${API_BASE_URL}/api/reaction-types`, {
headers: { Authorization: token ? `Bearer ${token}` : '' },
})
if (res.ok) {
reactionTypes.value = await res.json()
window.reactionTypes = [...reactionTypes.value]
isInitialized = true
} else {
reactionTypes.value = []
}
} catch (error) {
console.error('Failed to fetch reaction types:', error)
reactionTypes.value = []
} finally {
isLoading = false
}
return reactionTypes.value
}
const initialize = async () => {
if (!isInitialized) {
await fetchReactionTypes()
}
return reactionTypes.value
}
return {
reactionTypes: readonly(reactionTypes),
fetchReactionTypes,
initialize,
isInitialized: readonly(isInitialized)
}
}