Compare commits

..

16 Commits

Author SHA1 Message Date
Tim a3b28eafe4 Fix notification pagination after filtering disabled types 2025-08-19 19:48:41 +08:00
tim 805a8df7d3 Reapply "feat: add paginated notification endpoints"
This reverts commit e7a1e1d159.
2025-08-19 19:38:04 +08:00
tim 02be045f55 Revert "feat: add paginated notification APIs and frontend support"
This reverts commit c344b5b4ae.
2025-08-19 19:37:59 +08:00
Tim ac3c7b7bec Merge pull request #646 from nagisa77/codex/add-pagination-support-for-messages-6ssiwm
feat: add paginated notifications and unread endpoint
2025-08-19 19:35:39 +08:00
Tim c344b5b4ae feat: add paginated notification APIs and frontend support 2025-08-19 19:34:13 +08:00
tim e7a1e1d159 Revert "feat: add paginated notification endpoints"
This reverts commit cc525c1c27.
2025-08-19 19:33:13 +08:00
Tim 30b56e54cf Merge pull request #645 from nagisa77/codex/add-pagination-support-for-messages-owucez
feat: add paginated notification endpoints
2025-08-19 19:27:27 +08:00
Tim cc525c1c27 feat: add paginated notification endpoints 2025-08-19 19:27:07 +08:00
tim 3f2829cd37 Revert "feat: support paginated notifications"
This reverts commit a64fd71bbe.
2025-08-19 19:01:54 +08:00
Tim 3258a42b44 Merge pull request #644 from nagisa77/codex/add-pagination-support-for-messages
feat: paginate and load notifications per page
2025-08-19 18:46:12 +08:00
Tim a64fd71bbe feat: support paginated notifications 2025-08-19 18:45:56 +08:00
tim 1a12bec7b1 Revert "feat: add paginated notification APIs and frontend"
This reverts commit 7dd1f1b3d0.
2025-08-19 18:26:55 +08:00
Tim fbca19791a Merge pull request #643 from nagisa77/codex/add-pagination-support-for-message-page-ymy51v
feat: add paginated notification APIs and frontend
2025-08-19 18:25:10 +08:00
tim 10b6fdd1cb Revert "feat: add paginated notifications and unread endpoint"
This reverts commit 73168c1859.
2025-08-19 18:24:49 +08:00
Tim df92ff664c Merge pull request #642 from nagisa77/codex/add-pagination-support-for-message-page-2bmo7x
feat: add paginated notifications and unread endpoint
2025-08-19 18:20:39 +08:00
Tim 73168c1859 feat: add paginated notifications and unread endpoint 2025-08-19 18:20:26 +08:00
7 changed files with 321 additions and 305 deletions
@@ -24,16 +24,18 @@ public class NotificationController {
@GetMapping @GetMapping
public List<NotificationDto> list(@RequestParam(value = "page", defaultValue = "0") int page, public List<NotificationDto> list(@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "30") int size,
Authentication auth) { Authentication auth) {
return notificationService.listNotifications(auth.getName(), null, page).stream() return notificationService.listNotifications(auth.getName(), null, page, size).stream()
.map(notificationMapper::toDto) .map(notificationMapper::toDto)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@GetMapping("/unread") @GetMapping("/unread")
public List<NotificationDto> listUnread(@RequestParam(value = "page", defaultValue = "0") int page, public List<NotificationDto> listUnread(@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "30") int size,
Authentication auth) { Authentication auth) {
return notificationService.listNotifications(auth.getName(), false, page).stream() return notificationService.listNotifications(auth.getName(), false, page, size).stream()
.map(notificationMapper::toDto) .map(notificationMapper::toDto)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@@ -5,9 +5,9 @@ import com.openisle.model.User;
import com.openisle.model.Post; import com.openisle.model.Post;
import com.openisle.model.Comment; import com.openisle.model.Comment;
import com.openisle.model.NotificationType; import com.openisle.model.NotificationType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;
@@ -17,7 +17,10 @@ public interface NotificationRepository extends JpaRepository<Notification, Long
List<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read); List<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read);
Page<Notification> findByUserOrderByCreatedAtDesc(User user, Pageable pageable); Page<Notification> findByUserOrderByCreatedAtDesc(User user, Pageable pageable);
Page<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read, Pageable pageable); Page<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read, Pageable pageable);
Page<Notification> findByUserAndTypeNotInOrderByCreatedAtDesc(User user, java.util.Collection<NotificationType> types, Pageable pageable);
Page<Notification> findByUserAndReadAndTypeNotInOrderByCreatedAtDesc(User user, boolean read, java.util.Collection<NotificationType> types, Pageable pageable);
long countByUserAndRead(User user, boolean read); long countByUserAndRead(User user, boolean read);
long countByUserAndReadAndTypeNotIn(User user, boolean read, java.util.Collection<NotificationType> types);
List<Notification> findByPost(Post post); List<Notification> findByPost(Post post);
List<Notification> findByComment(Comment comment); List<Notification> findByComment(Comment comment);
@@ -23,7 +23,6 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.stream.Collectors;
/** Service for creating and retrieving notifications. */ /** Service for creating and retrieving notifications. */
@Service @Service
@@ -180,18 +179,26 @@ public class NotificationService {
userRepository.save(user); userRepository.save(user);
} }
public List<Notification> listNotifications(String username, Boolean read, int page) { public List<Notification> listNotifications(String username, Boolean read, int page, int size) {
User user = userRepository.findByUsername(username) User user = userRepository.findByUsername(username)
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found")); .orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
Set<NotificationType> disabled = user.getDisabledNotificationTypes(); Set<NotificationType> disabled = user.getDisabledNotificationTypes();
List<Notification> list; org.springframework.data.domain.Pageable pageable = org.springframework.data.domain.PageRequest.of(page, size);
var pageable = org.springframework.data.domain.PageRequest.of(page, 50); org.springframework.data.domain.Page<Notification> result;
if (read == null) { if (read == null) {
list = notificationRepository.findByUserOrderByCreatedAtDesc(user, pageable).getContent(); if (disabled.isEmpty()) {
result = notificationRepository.findByUserOrderByCreatedAtDesc(user, pageable);
} else {
result = notificationRepository.findByUserAndTypeNotInOrderByCreatedAtDesc(user, disabled, pageable);
}
} else { } else {
list = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable).getContent(); if (disabled.isEmpty()) {
result = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable);
} else {
result = notificationRepository.findByUserAndReadAndTypeNotInOrderByCreatedAtDesc(user, read, disabled, pageable);
}
} }
return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList()); return result.getContent();
} }
public void markRead(String username, List<Long> ids) { public void markRead(String username, List<Long> ids) {
@@ -210,8 +217,10 @@ public class NotificationService {
User user = userRepository.findByUsername(username) User user = userRepository.findByUsername(username)
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found")); .orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
Set<NotificationType> disabled = user.getDisabledNotificationTypes(); Set<NotificationType> disabled = user.getDisabledNotificationTypes();
return notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, false).stream() if (disabled.isEmpty()) {
.filter(n -> !disabled.contains(n.getType())).count(); return notificationRepository.countByUserAndRead(user, false);
}
return notificationRepository.countByUserAndReadAndTypeNotIn(user, false, disabled);
} }
public void notifyMentions(String content, User fromUser, Post post, Comment comment) { public void notifyMentions(String content, User fromUser, Post post, Comment comment) {
@@ -45,7 +45,7 @@ class NotificationControllerTest {
p.setId(2L); p.setId(2L);
n.setPost(p); n.setPost(p);
n.setCreatedAt(LocalDateTime.now()); n.setCreatedAt(LocalDateTime.now());
when(notificationService.listNotifications("alice", null)) when(notificationService.listNotifications("alice", null, 0, 30))
.thenReturn(List.of(n)); .thenReturn(List.of(n));
NotificationDto dto = new NotificationDto(); NotificationDto dto = new NotificationDto();
@@ -62,6 +62,24 @@ class NotificationControllerTest {
.andExpect(jsonPath("$[0].post.id").value(2)); .andExpect(jsonPath("$[0].post.id").value(2));
} }
@Test
void listUnreadNotifications() throws Exception {
Notification n = new Notification();
n.setId(5L);
n.setType(NotificationType.POST_VIEWED);
when(notificationService.listNotifications("alice", false, 0, 30))
.thenReturn(List.of(n));
NotificationDto dto = new NotificationDto();
dto.setId(5L);
when(notificationMapper.toDto(n)).thenReturn(dto);
mockMvc.perform(get("/api/notifications/unread")
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(5));
}
@Test @Test
void markReadEndpoint() throws Exception { void markReadEndpoint() throws Exception {
mockMvc.perform(post("/api/notifications/read") mockMvc.perform(post("/api/notifications/read")
@@ -11,6 +11,9 @@ import org.mockito.Mockito;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.HashSet;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@@ -62,15 +65,17 @@ class NotificationServiceTest {
User user = new User(); User user = new User();
user.setId(2L); user.setId(2L);
user.setUsername("bob"); user.setUsername("bob");
user.setDisabledNotificationTypes(new HashSet<>());
when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user)); when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user));
Notification n = new Notification(); Notification n = new Notification();
when(nRepo.findByUserOrderByCreatedAtDesc(user)).thenReturn(List.of(n)); when(nRepo.findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(n)));
List<Notification> list = service.listNotifications("bob", null); List<Notification> list = service.listNotifications("bob", null, 0, 10);
assertEquals(1, list.size()); assertEquals(1, list.size());
verify(nRepo).findByUserOrderByCreatedAtDesc(user); verify(nRepo).findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class));
} }
@Test @Test
@@ -87,6 +92,7 @@ class NotificationServiceTest {
User user = new User(); User user = new User();
user.setId(3L); user.setId(3L);
user.setUsername("carl"); user.setUsername("carl");
user.setDisabledNotificationTypes(new HashSet<>());
when(uRepo.findByUsername("carl")).thenReturn(Optional.of(user)); when(uRepo.findByUsername("carl")).thenReturn(Optional.of(user));
when(nRepo.countByUserAndRead(user, false)).thenReturn(5L); when(nRepo.countByUserAndRead(user, false)).thenReturn(5L);
@@ -96,6 +102,56 @@ class NotificationServiceTest {
verify(nRepo).countByUserAndRead(user, false); verify(nRepo).countByUserAndRead(user, false);
} }
@Test
void listNotificationsFiltersDisabledTypes() {
NotificationRepository nRepo = mock(NotificationRepository.class);
UserRepository uRepo = mock(UserRepository.class);
ReactionRepository rRepo = mock(ReactionRepository.class);
EmailSender email = mock(EmailSender.class);
PushNotificationService push = mock(PushNotificationService.class);
Executor executor = Runnable::run;
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
User user = new User();
user.setId(4L);
user.setUsername("dana");
when(uRepo.findByUsername("dana")).thenReturn(Optional.of(user));
Notification n = new Notification();
when(nRepo.findByUserAndTypeNotInOrderByCreatedAtDesc(eq(user), eq(user.getDisabledNotificationTypes()), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(n)));
List<Notification> list = service.listNotifications("dana", null, 0, 10);
assertEquals(1, list.size());
verify(nRepo).findByUserAndTypeNotInOrderByCreatedAtDesc(eq(user), eq(user.getDisabledNotificationTypes()), any(Pageable.class));
}
@Test
void countUnreadFiltersDisabledTypes() {
NotificationRepository nRepo = mock(NotificationRepository.class);
UserRepository uRepo = mock(UserRepository.class);
ReactionRepository rRepo = mock(ReactionRepository.class);
EmailSender email = mock(EmailSender.class);
PushNotificationService push = mock(PushNotificationService.class);
Executor executor = Runnable::run;
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
User user = new User();
user.setId(5L);
user.setUsername("erin");
when(uRepo.findByUsername("erin")).thenReturn(Optional.of(user));
when(nRepo.countByUserAndReadAndTypeNotIn(eq(user), eq(false), eq(user.getDisabledNotificationTypes())))
.thenReturn(2L);
long count = service.countUnread("erin");
assertEquals(2L, count);
verify(nRepo).countByUserAndReadAndTypeNotIn(eq(user), eq(false), eq(user.getDisabledNotificationTypes()));
}
@Test @Test
void createRegisterRequestNotificationsDeletesOldOnes() { void createRegisterRequestNotificationsDeletesOldOnes() {
NotificationRepository nRepo = mock(NotificationRepository.class); NotificationRepository nRepo = mock(NotificationRepository.class);
+37 -47
View File
@@ -53,13 +53,13 @@
</div> </div>
<BasePlaceholder <BasePlaceholder
v-else-if="displayNotifications.length === 0" v-else-if="notifications.length === 0"
text="暂时没有消息 :)" text="暂时没有消息 :)"
icon="fas fa-inbox" icon="fas fa-inbox"
/> />
<div class="timeline-container" v-if="displayNotifications.length > 0"> <div class="timeline-container" v-if="notifications.length > 0">
<BaseTimeline :items="displayNotifications"> <BaseTimeline :items="notifications">
<template #item="{ item }"> <template #item="{ item }">
<div class="notif-content" :class="{ read: item.read }"> <div class="notif-content" :class="{ read: item.read }">
<span v-if="!item.read" class="unread-dot"></span> <span v-if="!item.read" class="unread-dot"></span>
@@ -505,40 +505,31 @@
</div> </div>
</template> </template>
</BaseTimeline> </BaseTimeline>
<InfiniteLoadMore :key="selectedTab" :on-load="loadMore" :pause="isLoadingMessage" />
</div> </div>
<InfiniteLoadMore
v-if="displayNotifications.length > 0"
:key="ioKey"
:on-load="fetchNextPage"
:pause="isLoadingMessage"
root-margin="200px 0px"
/>
</template> </template>
</div> </div>
</template> </template>
<script setup> <script setup>
import { computed, onActivated, ref, watch } from 'vue' import { ref, watch, onActivated } from 'vue'
import BasePlaceholder from '~/components/BasePlaceholder.vue' import BasePlaceholder from '~/components/BasePlaceholder.vue'
import BaseTimeline from '~/components/BaseTimeline.vue' import BaseTimeline from '~/components/BaseTimeline.vue'
import NotificationContainer from '~/components/NotificationContainer.vue' import NotificationContainer from '~/components/NotificationContainer.vue'
import InfiniteLoadMore from '~/components/InfiniteLoadMore.vue'
import { toast } from '~/main' import { toast } from '~/main'
import { authState, getToken } from '~/utils/auth' import { authState, getToken } from '~/utils/auth'
import { stripMarkdownLength } from '~/utils/markdown' import { stripMarkdownLength } from '~/utils/markdown'
import InfiniteLoadMore from '~/components/InfiniteLoadMore.vue'
import { import {
fetchAllNotifications, fetchNotifications,
fetchUnreadNotifications,
fetchUnreadCount, fetchUnreadCount,
isLoadingAll, isLoadingMessage,
isLoadingUnread,
markRead, markRead,
allNotifications, notifications,
unreadNotifications,
markAllRead, markAllRead,
resetAll, hasMore,
resetUnread, fetchNotificationPreferences,
updateNotificationPreference,
} from '~/utils/notification' } from '~/utils/notification'
import TimeManager from '~/utils/time' import TimeManager from '~/utils/time'
@@ -549,25 +540,26 @@ const selectedTab = ref(
['all', 'unread', 'control'].includes(route.query.tab) ? route.query.tab : 'unread', ['all', 'unread', 'control'].includes(route.query.tab) ? route.query.tab : 'unread',
) )
const notificationPrefs = ref([]) const notificationPrefs = ref([])
const displayNotifications = computed(() => const page = ref(0)
selectedTab.value === 'all' ? allNotifications.value : unreadNotifications.value, const pageSize = 30
)
const isLoadingMessage = computed(() =>
selectedTab.value === 'all' ? isLoadingAll.value : isLoadingUnread.value,
)
const ioKey = ref(0)
const fetchNextPage = () => const loadMore = async () => {
selectedTab.value === 'all' ? fetchAllNotifications() : fetchUnreadNotifications() if (!hasMore.value) return true
page.value++
const loadInitial = async () => { await fetchNotifications({
if (selectedTab.value === 'all') { page: page.value,
if (allNotifications.value.length === 0) await fetchAllNotifications() size: pageSize,
} else if (selectedTab.value === 'unread') { unread: selectedTab.value === 'unread',
if (unreadNotifications.value.length === 0) await fetchUnreadNotifications() append: true,
} })
return !hasMore.value
} }
watch(selectedTab, async (tab) => {
page.value = 0
await fetchNotifications({ page: 0, size: pageSize, unread: tab === 'unread' })
})
const fetchPrefs = async () => { const fetchPrefs = async () => {
notificationPrefs.value = await fetchNotificationPreferences() notificationPrefs.value = await fetchNotificationPreferences()
} }
@@ -576,9 +568,11 @@ const togglePref = async (pref) => {
const ok = await updateNotificationPreference(pref.type, !pref.enabled) const ok = await updateNotificationPreference(pref.type, !pref.enabled)
if (ok) { if (ok) {
pref.enabled = !pref.enabled pref.enabled = !pref.enabled
resetAll() await fetchNotifications({
resetUnread() page: page.value,
await loadInitial() size: pageSize,
unread: selectedTab.value === 'unread',
})
await fetchUnreadCount() await fetchUnreadCount()
} else { } else {
toast.error('操作失败') toast.error('操作失败')
@@ -658,13 +652,9 @@ const formatType = (t) => {
} }
} }
watch(selectedTab, async () => { onActivated(async () => {
await loadInitial() page.value = 0
ioKey.value++ await fetchNotifications({ page: 0, size: pageSize, unread: selectedTab.value === 'unread' })
})
onActivated(() => {
loadInitial()
fetchPrefs() fetchPrefs()
}) })
</script> </script>
+180 -242
View File
@@ -4,7 +4,9 @@ import { toast } from '~/composables/useToast'
import { authState, getToken } from '~/utils/auth' import { authState, getToken } from '~/utils/auth'
import { reactionEmojiMap } from '~/utils/reactions' import { reactionEmojiMap } from '~/utils/reactions'
export const notificationState = reactive({ unreadCount: 0 }) export const notificationState = reactive({
unreadCount: 0,
})
const iconMap = { const iconMap = {
POST_VIEWED: 'fas fa-eye', POST_VIEWED: 'fas fa-eye',
@@ -55,6 +57,7 @@ export async function markNotificationsRead(ids) {
try { try {
const config = useRuntimeConfig() const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl const API_BASE_URL = config.public.apiBaseUrl
const token = getToken() const token = getToken()
if (!token || !ids || ids.length === 0) return false if (!token || !ids || ids.length === 0) return false
const res = await fetch(`${API_BASE_URL}/api/notifications/read`, { const res = await fetch(`${API_BASE_URL}/api/notifications/read`, {
@@ -75,6 +78,7 @@ export async function fetchNotificationPreferences() {
try { try {
const config = useRuntimeConfig() const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl const API_BASE_URL = config.public.apiBaseUrl
const token = getToken() const token = getToken()
if (!token) return [] if (!token) return []
const res = await fetch(`${API_BASE_URL}/api/notifications/prefs`, { const res = await fetch(`${API_BASE_URL}/api/notifications/prefs`, {
@@ -108,219 +112,180 @@ export async function updateNotificationPreference(type, enabled) {
} }
/** /**
* 提供通知列表的分页获取与状态管理 * 处理信息的高阶函数
* @returns
*/ */
function createFetchNotifications() { function createFetchNotifications() {
const allNotifications = ref([]) const notifications = ref([])
const unreadNotifications = ref([]) const isLoadingMessage = ref(false)
const pageAll = ref(0) const hasMore = ref(true)
const pageUnread = ref(0)
const isLoadingAll = ref(false)
const isLoadingUnread = ref(false)
const processAndPush = (data, target) => { const fetchNotifications = async ({
for (const n of data) { page = 0,
if (n.type === 'COMMENT_REPLY') { size = 30,
target.push({ unread = false,
...n, append = false,
src: n.comment.author.avatar, } = {}) => {
iconClick: () => { const config = useRuntimeConfig()
markRead(n.id) const API_BASE_URL = config.public.apiBaseUrl
navigateTo(`/users/${n.comment.author.id}`, { replace: true }) try {
}, const token = getToken()
}) if (!token) {
} else if (n.type === 'REACTION') { toast.error('请先登录')
target.push({ return
...n,
emoji: reactionEmojiMap[n.reactionType],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_VIEWED') {
target.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'LOTTERY_WIN') {
target.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'LOTTERY_DRAW') {
target.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_UPDATED') {
target.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'USER_ACTIVITY') {
target.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'MENTION') {
target.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'USER_FOLLOWED' || n.type === 'USER_UNFOLLOWED') {
target.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'FOLLOWED_POST') {
target.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_SUBSCRIBED' || n.type === 'POST_UNSUBSCRIBED') {
target.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_REVIEW_REQUEST') {
target.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'REGISTER_REQUEST') {
target.push({
...n,
icon: iconMap[n.type],
iconClick: () => {},
})
} else {
target.push({
...n,
icon: iconMap[n.type],
})
} }
} if (!append) notifications.value = []
} isLoadingMessage.value = true
const res = await fetch(
`${API_BASE_URL}/api/notifications${unread ? '/unread' : ''}?page=${page}&size=${size}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
)
isLoadingMessage.value = false
if (!res.ok) {
toast.error('获取通知失败')
return
}
const data = await res.json()
const arr = []
const fetchAllNotifications = async () => { for (const n of data) {
const config = useRuntimeConfig() if (n.type === 'COMMENT_REPLY') {
const API_BASE_URL = config.public.apiBaseUrl arr.push({
const token = getToken() ...n,
if (!token) { src: n.comment.author.avatar,
toast.error('请先登录') iconClick: () => {
return { done: true } markRead(n.id)
} navigateTo(`/users/${n.comment.author.id}`, { replace: true })
isLoadingAll.value = true },
const res = await fetch(`${API_BASE_URL}/api/notifications?page=${pageAll.value}`, { })
headers: { Authorization: `Bearer ${token}` }, } else if (n.type === 'REACTION') {
}) arr.push({
isLoadingAll.value = false ...n,
if (!res.ok) { emoji: reactionEmojiMap[n.reactionType],
toast.error('获取通知失败') iconClick: () => {
return { done: true } if (n.fromUser) {
} markRead(n.id)
const data = await res.json() navigateTo(`/users/${n.fromUser.id}`, { replace: true })
processAndPush(data, allNotifications.value) }
pageAll.value++ },
return { done: data.length < 50 } })
} } else if (n.type === 'POST_VIEWED') {
arr.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'LOTTERY_WIN' || n.type === 'LOTTERY_DRAW') {
arr.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`)
}
},
})
} else if (n.type === 'POST_UPDATED' || n.type === 'USER_ACTIVITY') {
arr.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'MENTION') {
arr.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'USER_FOLLOWED' || n.type === 'USER_UNFOLLOWED') {
arr.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (
n.type === 'FOLLOWED_POST' ||
n.type === 'POST_SUBSCRIBED' ||
n.type === 'POST_UNSUBSCRIBED'
) {
arr.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_REVIEW_REQUEST') {
arr.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'REGISTER_REQUEST') {
arr.push({
...n,
icon: iconMap[n.type],
iconClick: () => {},
})
} else {
arr.push({
...n,
icon: iconMap[n.type],
})
}
}
const fetchUnreadNotifications = async () => { if (append) notifications.value.push(...arr)
const config = useRuntimeConfig() else notifications.value = arr
const API_BASE_URL = config.public.apiBaseUrl hasMore.value = data.length === size
const token = getToken() } catch (e) {
if (!token) { console.error(e)
toast.error('请先登录') isLoadingMessage.value = false
return { done: true }
} }
isLoadingUnread.value = true
const res = await fetch(`${API_BASE_URL}/api/notifications/unread?page=${pageUnread.value}`, {
headers: { Authorization: `Bearer ${token}` },
})
isLoadingUnread.value = false
if (!res.ok) {
toast.error('获取通知失败')
return { done: true }
}
const data = await res.json()
processAndPush(data, unreadNotifications.value)
pageUnread.value++
return { done: data.length < 50 }
} }
const markRead = async (id) => { const markRead = async (id) => {
if (!id) return if (!id) return
const nAll = allNotifications.value.find((n) => n.id === id) const n = notifications.value.find((n) => n.id === id)
const idxUnread = unreadNotifications.value.findIndex((n) => n.id === id) if (!n || n.read) return
const unreadItem = idxUnread !== -1 ? unreadNotifications.value[idxUnread] : null n.read = true
if (nAll) nAll.read = true
if (idxUnread !== -1) unreadNotifications.value.splice(idxUnread, 1)
if (notificationState.unreadCount > 0) notificationState.unreadCount-- if (notificationState.unreadCount > 0) notificationState.unreadCount--
const ok = await markNotificationsRead([id]) const ok = await markNotificationsRead([id])
if (!ok) { if (!ok) {
if (nAll) nAll.read = false n.read = false
if (idxUnread !== -1 && unreadItem) unreadNotifications.value.splice(idxUnread, 0, unreadItem)
notificationState.unreadCount++ notificationState.unreadCount++
} else { } else {
fetchUnreadCount() fetchUnreadCount()
@@ -328,28 +293,20 @@ function createFetchNotifications() {
} }
const markAllRead = async () => { const markAllRead = async () => {
const idsToMark = [ // 除了 REGISTER_REQUEST 类型消息
...new Set( const idsToMark = notifications.value
[...allNotifications.value, ...unreadNotifications.value] .filter((n) => n.type !== 'REGISTER_REQUEST' && !n.read)
.filter((n) => n.type !== 'REGISTER_REQUEST' && !n.read) .map((n) => n.id)
.map((n) => n.id),
),
]
if (idsToMark.length === 0) return if (idsToMark.length === 0) return
allNotifications.value.forEach((n) => { notifications.value.forEach((n) => {
if (n.type !== 'REGISTER_REQUEST') n.read = true if (n.type !== 'REGISTER_REQUEST') n.read = true
}) })
const prevUnread = [...unreadNotifications.value] notificationState.unreadCount = notifications.value.filter((n) => !n.read).length
unreadNotifications.value = unreadNotifications.value.filter(
(n) => n.type === 'REGISTER_REQUEST',
)
notificationState.unreadCount = unreadNotifications.value.length
const ok = await markNotificationsRead(idsToMark) const ok = await markNotificationsRead(idsToMark)
if (!ok) { if (!ok) {
allNotifications.value.forEach((n) => { notifications.value.forEach((n) => {
if (idsToMark.includes(n.id)) n.read = false if (idsToMark.includes(n.id)) n.read = false
}) })
unreadNotifications.value = prevUnread
await fetchUnreadCount() await fetchUnreadCount()
return return
} }
@@ -360,40 +317,21 @@ function createFetchNotifications() {
toast.success('已读所有消息') toast.success('已读所有消息')
} }
} }
const resetAll = () => {
pageAll.value = 0
allNotifications.value = []
}
const resetUnread = () => {
pageUnread.value = 0
unreadNotifications.value = []
}
return { return {
fetchAllNotifications, fetchNotifications,
fetchUnreadNotifications,
markRead, markRead,
notifications,
isLoadingMessage,
markAllRead, markAllRead,
allNotifications, hasMore,
unreadNotifications,
isLoadingAll,
isLoadingUnread,
resetAll,
resetUnread,
} }
} }
export const { export const {
fetchAllNotifications, fetchNotifications,
fetchUnreadNotifications,
markRead, markRead,
notifications,
isLoadingMessage,
markAllRead, markAllRead,
allNotifications, hasMore,
unreadNotifications,
isLoadingAll,
isLoadingUnread,
resetAll,
resetUnread,
} = createFetchNotifications() } = createFetchNotifications()