1.0
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { momentsApi } from '@/api/moments'
|
||||
|
||||
export const useMomentsStore = defineStore('moments', () => {
|
||||
const feed = ref<any[]>([])
|
||||
const isLoading = ref(false)
|
||||
const hasMore = ref(true)
|
||||
const cursor = ref<string | null>(null)
|
||||
|
||||
async function fetchFeed(refresh = false) {
|
||||
if (isLoading.value) return
|
||||
if (!refresh && !hasMore.value) return
|
||||
|
||||
isLoading.value = true
|
||||
try {
|
||||
if (refresh) {
|
||||
cursor.value = null
|
||||
feed.value = []
|
||||
hasMore.value = true
|
||||
}
|
||||
const { data } = await momentsApi.getFeed(cursor.value || undefined)
|
||||
if (refresh) {
|
||||
feed.value = data
|
||||
} else {
|
||||
feed.value = [...feed.value, ...data]
|
||||
}
|
||||
if (data.length > 0) {
|
||||
cursor.value = data[data.length - 1].id
|
||||
}
|
||||
if (data.length < 20) {
|
||||
hasMore.value = false
|
||||
}
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function createMoment(content: string, images?: string[], visibility?: string) {
|
||||
const { data } = await momentsApi.createMoment({ content, images, visibility })
|
||||
feed.value.unshift(data)
|
||||
return data
|
||||
}
|
||||
|
||||
async function toggleLike(momentId: string) {
|
||||
const { data } = await momentsApi.toggleLike(momentId)
|
||||
const moment = feed.value.find((m) => m.id === momentId)
|
||||
if (moment) {
|
||||
moment.is_liked = data.is_liked
|
||||
moment.like_count = data.is_liked ? moment.like_count + 1 : Math.max(0, moment.like_count - 1)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
async function addComment(momentId: string, content: string, replyToId?: string) {
|
||||
const { data } = await momentsApi.addComment(momentId, content, replyToId)
|
||||
const moment = feed.value.find((m) => m.id === momentId)
|
||||
if (moment) {
|
||||
moment.comment_count = (moment.comment_count || 0) + 1
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
async function deleteMoment(momentId: string) {
|
||||
await momentsApi.deleteMoment(momentId)
|
||||
feed.value = feed.value.filter((m) => m.id !== momentId)
|
||||
}
|
||||
|
||||
return {
|
||||
feed, isLoading, hasMore,
|
||||
fetchFeed, createMoment, toggleLike, addComment, deleteMoment,
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user