Merge pull request #644 from nagisa77/codex/add-pagination-support-for-messages

feat: paginate and load notifications per page
This commit is contained in:
Tim
2025-08-19 18:46:12 +08:00
committed by GitHub
7 changed files with 255 additions and 186 deletions

View File

@@ -23,9 +23,19 @@ public class NotificationController {
private final NotificationMapper notificationMapper; private final NotificationMapper notificationMapper;
@GetMapping @GetMapping
public List<NotificationDto> list(@RequestParam(value = "read", required = false) Boolean read, 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(), read).stream() return notificationService.listNotifications(auth.getName(), page, size).stream()
.map(notificationMapper::toDto)
.collect(Collectors.toList());
}
@GetMapping("/unread")
public List<NotificationDto> listUnread(@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "30") int size,
Authentication auth) {
return notificationService.listUnreadNotifications(auth.getName(), page, size).stream()
.map(notificationMapper::toDto) .map(notificationMapper::toDto)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }

View File

@@ -5,6 +5,8 @@ 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.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;
@@ -13,6 +15,8 @@ import java.util.List;
public interface NotificationRepository extends JpaRepository<Notification, Long> { public interface NotificationRepository extends JpaRepository<Notification, Long> {
List<Notification> findByUserOrderByCreatedAtDesc(User user); List<Notification> findByUserOrderByCreatedAtDesc(User user);
List<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read); List<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read);
Page<Notification> findByUser(User user, Pageable pageable);
Page<Notification> findByUserAndRead(User user, boolean read, Pageable pageable);
long countByUserAndRead(User user, boolean read); long countByUserAndRead(User user, boolean read);
List<Notification> findByPost(Post post); List<Notification> findByPost(Post post);
List<Notification> findByComment(Comment comment); List<Notification> findByComment(Comment comment);

View File

@@ -24,6 +24,10 @@ 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; import java.util.stream.Collectors;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
/** Service for creating and retrieving notifications. */ /** Service for creating and retrieving notifications. */
@Service @Service
@@ -180,15 +184,24 @@ public class NotificationService {
userRepository.save(user); userRepository.save(user);
} }
public List<Notification> listNotifications(String username, Boolean read) { public List<Notification> listNotifications(String username, int page, int size) {
return listNotifications(username, null, page, size);
}
public List<Notification> listUnreadNotifications(String username, int page, int size) {
return listNotifications(username, false, page, size);
}
private 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; Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
Page<Notification> list;
if (read == null) { if (read == null) {
list = notificationRepository.findByUserOrderByCreatedAtDesc(user); list = notificationRepository.findByUser(user, pageable);
} else { } else {
list = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read); list = notificationRepository.findByUserAndRead(user, read, pageable);
} }
return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList()); return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
} }

View File

@@ -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", 0, 30))
.thenReturn(List.of(n)); .thenReturn(List.of(n));
NotificationDto dto = new NotificationDto(); NotificationDto dto = new NotificationDto();
@@ -62,6 +62,23 @@ 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(1L);
when(notificationService.listUnreadNotifications("alice", 0, 30))
.thenReturn(List.of(n));
NotificationDto dto = new NotificationDto();
dto.setId(1L);
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(1));
}
@Test @Test
void markReadEndpoint() throws Exception { void markReadEndpoint() throws Exception {
mockMvc.perform(post("/api/notifications/read") mockMvc.perform(post("/api/notifications/read")

View File

@@ -11,6 +11,7 @@ import org.mockito.Mockito;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
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.*;
@@ -65,12 +66,12 @@ class NotificationServiceTest {
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.findByUser(eq(user), any(Pageable.class))).thenReturn(new org.springframework.data.domain.PageImpl<>(List.of(n)));
List<Notification> list = service.listNotifications("bob", null); List<Notification> list = service.listNotifications("bob", 0, 30);
assertEquals(1, list.size()); assertEquals(1, list.size());
verify(nRepo).findByUserOrderByCreatedAtDesc(user); verify(nRepo).findByUser(eq(user), any(Pageable.class));
} }
@Test @Test

View File

@@ -53,13 +53,13 @@
</div> </div>
<BasePlaceholder <BasePlaceholder
v-else-if="filteredNotifications.length === 0" v-else-if="notifications.length === 0"
text="暂时没有消息 :)" text="暂时没有消息 :)"
icon="fas fa-inbox" icon="fas fa-inbox"
/> />
<div class="timeline-container" v-if="filteredNotifications.length > 0"> <div class="timeline-container" v-if="notifications.length > 0">
<BaseTimeline :items="filteredNotifications"> <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,15 +505,17 @@
</div> </div>
</template> </template>
</BaseTimeline> </BaseTimeline>
<InfiniteLoadMore :key="selectedTab" :on-load="fetchMore" :pause="isLoadingMessage" />
</div> </div>
</template> </template>
</div> </div>
</template> </template>
<script setup> <script setup>
import { computed, onMounted, ref } 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 InfiniteLoadMore from '~/components/InfiniteLoadMore.vue'
import NotificationContainer from '~/components/NotificationContainer.vue' import NotificationContainer from '~/components/NotificationContainer.vue'
import { toast } from '~/main' import { toast } from '~/main'
import { authState, getToken } from '~/utils/auth' import { authState, getToken } from '~/utils/auth'
@@ -525,6 +527,8 @@ import {
markRead, markRead,
notifications, notifications,
markAllRead, markAllRead,
fetchNotificationPreferences,
updateNotificationPreference,
} from '~/utils/notification' } from '~/utils/notification'
import TimeManager from '~/utils/time' import TimeManager from '~/utils/time'
@@ -535,9 +539,16 @@ 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 filteredNotifications = computed(() =>
selectedTab.value === 'all' ? notifications.value : notifications.value.filter((n) => !n.read), const fetchMore = () => fetchNotifications()
)
const loadInitial = async () => {
await fetchNotifications({ reset: true, read: selectedTab.value === 'unread' ? false : null })
}
watch(selectedTab, async (t) => {
await fetchNotifications({ reset: true, read: t === 'unread' ? false : null })
})
const fetchPrefs = async () => { const fetchPrefs = async () => {
notificationPrefs.value = await fetchNotificationPreferences() notificationPrefs.value = await fetchNotificationPreferences()
@@ -547,7 +558,7 @@ 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
await fetchNotifications() await fetchNotifications({ reset: true, read: selectedTab.value === 'unread' ? false : null })
await fetchUnreadCount() await fetchUnreadCount()
} else { } else {
toast.error('操作失败') toast.error('操作失败')
@@ -628,7 +639,7 @@ const formatType = (t) => {
} }
onActivated(() => { onActivated(() => {
fetchNotifications() loadInitial()
fetchPrefs() fetchPrefs()
}) })
</script> </script>

View File

@@ -118,175 +118,189 @@ export async function updateNotificationPreference(type, enabled) {
function createFetchNotifications() { function createFetchNotifications() {
const notifications = ref([]) const notifications = ref([])
const isLoadingMessage = ref(false) const isLoadingMessage = ref(false)
const fetchNotifications = async () => { const page = ref(0)
const pageSize = 30
const readFilter = ref(null)
const fetchNotifications = async ({ reset = false, read = null } = {}) => {
const config = useRuntimeConfig() const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl const API_BASE_URL = config.public.apiBaseUrl
if (isLoadingMessage && notifications && markRead) { if (isLoadingMessage.value) return false
try { try {
const token = getToken() const token = getToken()
if (!token) { if (!token) {
toast.error('请先登录') toast.error('请先登录')
return return true
}
isLoadingMessage.value = true
notifications.value = []
const res = await fetch(`${API_BASE_URL}/api/notifications`, {
headers: {
Authorization: `Bearer ${token}`,
},
})
isLoadingMessage.value = false
if (!res.ok) {
toast.error('获取通知失败')
return
}
const data = await res.json()
for (const n of data) {
if (n.type === 'COMMENT_REPLY') {
notifications.value.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'REACTION') {
notifications.value.push({
...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') {
notifications.value.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') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
router.push(`/posts/${n.post.id}`)
}
},
})
} else if (n.type === 'LOTTERY_DRAW') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
router.push(`/posts/${n.post.id}`)
}
},
})
} else if (n.type === 'POST_UPDATED') {
notifications.value.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') {
notifications.value.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'MENTION') {
notifications.value.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') {
notifications.value.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') {
notifications.value.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') {
notifications.value.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') {
notifications.value.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') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {},
})
} else {
notifications.value.push({
...n,
icon: iconMap[n.type],
})
}
}
} catch (e) {
console.error(e)
} }
if (reset) {
notifications.value = []
page.value = 0
readFilter.value = read
}
isLoadingMessage.value = true
let url = `${API_BASE_URL}/api/notifications`
if (readFilter.value === false) url += '/unread'
url += `?page=${page.value}&size=${pageSize}`
const res = await fetch(url, {
headers: {
Authorization: `Bearer ${token}`,
},
})
isLoadingMessage.value = false
if (!res.ok) {
toast.error('获取通知失败')
return true
}
const data = await res.json()
for (const n of data) {
if (n.type === 'COMMENT_REPLY') {
notifications.value.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'REACTION') {
notifications.value.push({
...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') {
notifications.value.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') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
router.push(`/posts/${n.post.id}`)
}
},
})
} else if (n.type === 'LOTTERY_DRAW') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
router.push(`/posts/${n.post.id}`)
}
},
})
} else if (n.type === 'POST_UPDATED') {
notifications.value.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') {
notifications.value.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'MENTION') {
notifications.value.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') {
notifications.value.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') {
notifications.value.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') {
notifications.value.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') {
notifications.value.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') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {},
})
} else {
notifications.value.push({
...n,
icon: iconMap[n.type],
})
}
}
const done = data.length < pageSize
if (!done) page.value++
return done
} catch (e) {
console.error(e)
isLoadingMessage.value = false
return true
} }
} }
@@ -335,7 +349,6 @@ function createFetchNotifications() {
markRead, markRead,
notifications, notifications,
isLoadingMessage, isLoadingMessage,
markRead,
markAllRead, markAllRead,
} }
} }