Compare commits

...

4 Commits

Author SHA1 Message Date
Tim
73168c1859 feat: add paginated notifications and unread endpoint 2025-08-19 18:20:26 +08:00
tim
77856ff9af fix: make full page 2025-08-19 17:23:50 +08:00
tim
df49b21620 Revert "feat: add paginated notification API and frontend support"
This reverts commit df7ca77652.
2025-08-19 17:23:36 +08:00
Tim
fbe2c66955 Merge pull request #641 from nagisa77/codex/add-pagination-support-for-message-page
feat: paginate notifications and add unread filter
2025-08-19 17:08:05 +08:00
7 changed files with 230 additions and 233 deletions

View File

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

View File

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

View File

@@ -26,6 +26,8 @@ import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
/** Service for creating and retrieving notifications. */
@Service
@@ -182,22 +184,19 @@ public class NotificationService {
userRepository.save(user);
}
public List<Notification> listNotifications(String username, Boolean read) {
return listNotifications(username, read, 0);
}
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)
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
Set<NotificationType> disabled = user.getDisabledNotificationTypes();
Page<Notification> p;
Pageable pageable = org.springframework.data.domain.PageRequest.of(page, 50);
Pageable pageable = PageRequest.of(page, size,
Sort.by(Sort.Direction.DESC, "createdAt"));
Page<Notification> pg;
if (read == null) {
p = notificationRepository.findByUserOrderByCreatedAtDesc(user, pageable);
pg = notificationRepository.findByUser(user, pageable);
} else {
p = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable);
pg = notificationRepository.findByUserAndRead(user, read, pageable);
}
return p.getContent().stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
return pg.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
}
public void markRead(String username, List<Long> ids) {

View File

@@ -45,7 +45,7 @@ class NotificationControllerTest {
p.setId(2L);
n.setPost(p);
n.setCreatedAt(LocalDateTime.now());
when(notificationService.listNotifications("alice", null, 0))
when(notificationService.listNotifications("alice", null, 0, 50))
.thenReturn(List.of(n));
NotificationDto dto = new NotificationDto();
@@ -55,7 +55,7 @@ class NotificationControllerTest {
dto.setPost(ps);
when(notificationMapper.toDto(n)).thenReturn(dto);
mockMvc.perform(get("/api/notifications")
mockMvc.perform(get("/api/notifications?page=0")
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(1))
@@ -65,18 +65,27 @@ class NotificationControllerTest {
@Test
void listUnreadNotifications() throws Exception {
Notification n = new Notification();
n.setId(3L);
n.setId(1L);
n.setType(NotificationType.POST_VIEWED);
when(notificationService.listNotifications("alice", false, 0)).thenReturn(List.of(n));
Post p = new Post();
p.setId(2L);
n.setPost(p);
n.setCreatedAt(LocalDateTime.now());
when(notificationService.listNotifications("alice", false, 0, 50))
.thenReturn(List.of(n));
NotificationDto dto = new NotificationDto();
dto.setId(3L);
dto.setId(1L);
PostSummaryDto ps = new PostSummaryDto();
ps.setId(2L);
dto.setPost(ps);
when(notificationMapper.toDto(n)).thenReturn(dto);
mockMvc.perform(get("/api/notifications/unread")
.principal(new UsernamePasswordAuthenticationToken("alice", "p")))
mockMvc.perform(get("/api/notifications/unread?page=0")
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(3));
.andExpect(jsonPath("$[0].id").value(1))
.andExpect(jsonPath("$[0].post.id").value(2));
}
@Test

View File

@@ -65,15 +65,12 @@ class NotificationServiceTest {
when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user));
Notification n = new Notification();
org.springframework.data.domain.Page<Notification> page =
new org.springframework.data.domain.PageImpl<>(List.of(n));
when(nRepo.findByUserOrderByCreatedAtDesc(eq(user), any(org.springframework.data.domain.Pageable.class)))
.thenReturn(page);
when(nRepo.findByUser(eq(user), any())).thenReturn(new org.springframework.data.domain.PageImpl<>(List.of(n)));
List<Notification> list = service.listNotifications("bob", null);
List<Notification> list = service.listNotifications("bob", null, 0, 50);
assertEquals(1, list.size());
verify(nRepo).findByUserOrderByCreatedAtDesc(eq(user), any(org.springframework.data.domain.Pageable.class));
verify(nRepo).findByUser(eq(user), any());
}
@Test

View File

@@ -505,14 +505,19 @@
</div>
</template>
</BaseTimeline>
<InfiniteLoadMore :key="ioKey" :on-load="fetchNextPage" :pause="isLoadingMessage" />
<InfiniteLoadMore
:key="ioKey"
:on-load="fetchNextPage"
:pause="isLoadingMessage"
root-margin="200px 0px"
/>
</div>
</template>
</div>
</template>
<script setup>
import { onActivated, ref, watch } from 'vue'
import { computed, onActivated, ref, watch } from 'vue'
import BasePlaceholder from '~/components/BasePlaceholder.vue'
import BaseTimeline from '~/components/BaseTimeline.vue'
import NotificationContainer from '~/components/NotificationContainer.vue'
@@ -527,8 +532,6 @@ import {
markRead,
notifications,
markAllRead,
fetchNotificationPreferences,
updateNotificationPreference,
} from '~/utils/notification'
import TimeManager from '~/utils/time'
@@ -539,7 +542,11 @@ const selectedTab = ref(
['all', 'unread', 'control'].includes(route.query.tab) ? route.query.tab : 'unread',
)
const notificationPrefs = ref([])
const ioKey = ref(0)
const ioKey = computed(() => selectedTab.value)
const loadFirstPage = async () => {
await fetchNotifications({ unread: selectedTab.value === 'unread', reset: true })
}
const fetchNextPage = async () => fetchNotifications()
const fetchPrefs = async () => {
notificationPrefs.value = await fetchNotificationPreferences()
@@ -549,7 +556,7 @@ const togglePref = async (pref) => {
const ok = await updateNotificationPreference(pref.type, !pref.enabled)
if (ok) {
pref.enabled = !pref.enabled
await fetchNotifications(selectedTab.value, true)
await fetchNotifications({ unread: selectedTab.value === 'unread', reset: true })
await fetchUnreadCount()
} else {
toast.error('操作失败')
@@ -629,21 +636,14 @@ const formatType = (t) => {
}
}
watch(selectedTab, (val) => {
if (val !== 'control') loadFirstPage()
})
onActivated(() => {
fetchNotifications(selectedTab.value, true)
if (selectedTab.value !== 'control') loadFirstPage()
fetchPrefs()
})
watch(selectedTab, (tab) => {
if (tab !== 'control') {
fetchNotifications(tab, true)
} else {
fetchPrefs()
}
ioKey.value++
})
const fetchNextPage = () => fetchNotifications(selectedTab.value)
</script>
<style scoped>
@@ -657,8 +657,6 @@ const fetchNextPage = () => fetchNotifications(selectedTab.value)
.message-page {
background-color: var(--background-color);
overflow-x: hidden;
height: calc(100vh - var(--header-height));
overflow-y: auto;
}
.message-page-header {

View File

@@ -119,194 +119,188 @@ function createFetchNotifications() {
const notifications = ref([])
const isLoadingMessage = ref(false)
const page = ref(0)
const finished = ref(false)
const currentTab = ref('all')
const fetchNotifications = async (tab = 'all', reset = false) => {
const currentUnread = ref(false)
const fetchNotifications = async ({ unread = false, reset = false } = {}) => {
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
try {
const token = getToken()
if (!token) {
toast.error('请先登录')
return true
}
if (reset || tab !== currentTab.value) {
notifications.value = []
page.value = 0
finished.value = false
currentTab.value = tab
}
if (finished.value) return true
isLoadingMessage.value = true
let url = `${API_BASE_URL}/api/notifications`
if (currentTab.value === 'unread') url += '/unread'
url += `?page=${page.value}`
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)
navigateTo(`/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)
navigateTo(`/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],
})
if (isLoadingMessage && notifications && markRead) {
try {
const token = getToken()
if (!token) {
toast.error('请先登录')
return false
}
if (reset) {
notifications.value = []
page.value = 0
currentUnread.value = unread
}
isLoadingMessage.value = true
const endpoint = currentUnread.value
? `/api/notifications/unread?page=${page.value}`
: `/api/notifications?page=${page.value}`
const res = await fetch(`${API_BASE_URL}${endpoint}`, {
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 < 50
if (!done) {
page.value++
} else {
finished.value = true
return data.length < 50
} catch (e) {
console.error(e)
return true
}
return done
} catch (e) {
console.error(e)
isLoadingMessage.value = false
return true
}
return true
}
const markRead = async (id) => {