mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-07-24 13:36:28 +00:00
Revert "feat: add paginated notifications and unread endpoint"
This reverts commit 73168c1859.
This commit is contained in:
@@ -24,17 +24,8 @@ public class NotificationController {
|
|||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public List<NotificationDto> list(@RequestParam(value = "read", required = false) Boolean read,
|
public List<NotificationDto> list(@RequestParam(value = "read", required = false) Boolean read,
|
||||||
@RequestParam(value = "page", defaultValue = "0") int page,
|
|
||||||
Authentication auth) {
|
Authentication auth) {
|
||||||
return notificationService.listNotifications(auth.getName(), read, page, 50).stream()
|
return notificationService.listNotifications(auth.getName(), read).stream()
|
||||||
.map(notificationMapper::toDto)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/unread")
|
|
||||||
public List<NotificationDto> listUnread(@RequestParam(value = "page", defaultValue = "0") int page,
|
|
||||||
Authentication auth) {
|
|
||||||
return notificationService.listNotifications(auth.getName(), false, page, 50).stream()
|
|
||||||
.map(notificationMapper::toDto)
|
.map(notificationMapper::toDto)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,6 @@ 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.jpa.repository.JpaRepository;
|
||||||
import org.springframework.data.domain.Page;
|
|
||||||
import org.springframework.data.domain.Pageable;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@@ -15,8 +13,6 @@ 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);
|
||||||
|
|||||||
@@ -24,10 +24,6 @@ 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.Pageable;
|
|
||||||
import org.springframework.data.domain.PageRequest;
|
|
||||||
import org.springframework.data.domain.Sort;
|
|
||||||
|
|
||||||
/** Service for creating and retrieving notifications. */
|
/** Service for creating and retrieving notifications. */
|
||||||
@Service
|
@Service
|
||||||
@@ -184,19 +180,17 @@ public class NotificationService {
|
|||||||
userRepository.save(user);
|
userRepository.save(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Notification> listNotifications(String username, Boolean read, int page, int size) {
|
public List<Notification> listNotifications(String username, Boolean read) {
|
||||||
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();
|
||||||
Pageable pageable = PageRequest.of(page, size,
|
List<Notification> list;
|
||||||
Sort.by(Sort.Direction.DESC, "createdAt"));
|
|
||||||
Page<Notification> pg;
|
|
||||||
if (read == null) {
|
if (read == null) {
|
||||||
pg = notificationRepository.findByUser(user, pageable);
|
list = notificationRepository.findByUserOrderByCreatedAtDesc(user);
|
||||||
} else {
|
} else {
|
||||||
pg = notificationRepository.findByUserAndRead(user, read, pageable);
|
list = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read);
|
||||||
}
|
}
|
||||||
return pg.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
|
return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
public void markRead(String username, List<Long> ids) {
|
public void markRead(String username, List<Long> ids) {
|
||||||
|
|||||||
@@ -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, 0, 50))
|
when(notificationService.listNotifications("alice", null))
|
||||||
.thenReturn(List.of(n));
|
.thenReturn(List.of(n));
|
||||||
|
|
||||||
NotificationDto dto = new NotificationDto();
|
NotificationDto dto = new NotificationDto();
|
||||||
@@ -55,33 +55,7 @@ class NotificationControllerTest {
|
|||||||
dto.setPost(ps);
|
dto.setPost(ps);
|
||||||
when(notificationMapper.toDto(n)).thenReturn(dto);
|
when(notificationMapper.toDto(n)).thenReturn(dto);
|
||||||
|
|
||||||
mockMvc.perform(get("/api/notifications?page=0")
|
mockMvc.perform(get("/api/notifications")
|
||||||
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andExpect(jsonPath("$[0].id").value(1))
|
|
||||||
.andExpect(jsonPath("$[0].post.id").value(2));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void listUnreadNotifications() throws Exception {
|
|
||||||
Notification n = new Notification();
|
|
||||||
n.setId(1L);
|
|
||||||
n.setType(NotificationType.POST_VIEWED);
|
|
||||||
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(1L);
|
|
||||||
PostSummaryDto ps = new PostSummaryDto();
|
|
||||||
ps.setId(2L);
|
|
||||||
dto.setPost(ps);
|
|
||||||
when(notificationMapper.toDto(n)).thenReturn(dto);
|
|
||||||
|
|
||||||
mockMvc.perform(get("/api/notifications/unread?page=0")
|
|
||||||
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
|
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
|
||||||
.andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
.andExpect(jsonPath("$[0].id").value(1))
|
.andExpect(jsonPath("$[0].id").value(1))
|
||||||
|
|||||||
@@ -65,12 +65,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.findByUser(eq(user), any())).thenReturn(new org.springframework.data.domain.PageImpl<>(List.of(n)));
|
when(nRepo.findByUserOrderByCreatedAtDesc(user)).thenReturn(List.of(n));
|
||||||
|
|
||||||
List<Notification> list = service.listNotifications("bob", null, 0, 50);
|
List<Notification> list = service.listNotifications("bob", null);
|
||||||
|
|
||||||
assertEquals(1, list.size());
|
assertEquals(1, list.size());
|
||||||
verify(nRepo).findByUser(eq(user), any());
|
verify(nRepo).findByUserOrderByCreatedAtDesc(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -53,13 +53,13 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<BasePlaceholder
|
<BasePlaceholder
|
||||||
v-else-if="notifications.length === 0"
|
v-else-if="filteredNotifications.length === 0"
|
||||||
text="暂时没有消息 :)"
|
text="暂时没有消息 :)"
|
||||||
icon="fas fa-inbox"
|
icon="fas fa-inbox"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div class="timeline-container" v-if="notifications.length > 0">
|
<div class="timeline-container" v-if="filteredNotifications.length > 0">
|
||||||
<BaseTimeline :items="notifications">
|
<BaseTimeline :items="filteredNotifications">
|
||||||
<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,23 +505,16 @@
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</BaseTimeline>
|
</BaseTimeline>
|
||||||
<InfiniteLoadMore
|
|
||||||
:key="ioKey"
|
|
||||||
:on-load="fetchNextPage"
|
|
||||||
:pause="isLoadingMessage"
|
|
||||||
root-margin="200px 0px"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { computed, onActivated, ref, watch } from 'vue'
|
import { computed, onMounted, ref } 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'
|
||||||
@@ -542,11 +535,9 @@ 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 ioKey = computed(() => selectedTab.value)
|
const filteredNotifications = computed(() =>
|
||||||
const loadFirstPage = async () => {
|
selectedTab.value === 'all' ? notifications.value : notifications.value.filter((n) => !n.read),
|
||||||
await fetchNotifications({ unread: selectedTab.value === 'unread', reset: true })
|
)
|
||||||
}
|
|
||||||
const fetchNextPage = async () => fetchNotifications()
|
|
||||||
|
|
||||||
const fetchPrefs = async () => {
|
const fetchPrefs = async () => {
|
||||||
notificationPrefs.value = await fetchNotificationPreferences()
|
notificationPrefs.value = await fetchNotificationPreferences()
|
||||||
@@ -556,7 +547,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({ unread: selectedTab.value === 'unread', reset: true })
|
await fetchNotifications()
|
||||||
await fetchUnreadCount()
|
await fetchUnreadCount()
|
||||||
} else {
|
} else {
|
||||||
toast.error('操作失败')
|
toast.error('操作失败')
|
||||||
@@ -636,12 +627,8 @@ const formatType = (t) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
watch(selectedTab, (val) => {
|
|
||||||
if (val !== 'control') loadFirstPage()
|
|
||||||
})
|
|
||||||
|
|
||||||
onActivated(() => {
|
onActivated(() => {
|
||||||
if (selectedTab.value !== 'control') loadFirstPage()
|
fetchNotifications()
|
||||||
fetchPrefs()
|
fetchPrefs()
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -118,9 +118,7 @@ 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 page = ref(0)
|
const fetchNotifications = async () => {
|
||||||
const currentUnread = ref(false)
|
|
||||||
const fetchNotifications = async ({ unread = false, reset = false } = {}) => {
|
|
||||||
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 && notifications && markRead) {
|
||||||
@@ -128,18 +126,11 @@ function createFetchNotifications() {
|
|||||||
const token = getToken()
|
const token = getToken()
|
||||||
if (!token) {
|
if (!token) {
|
||||||
toast.error('请先登录')
|
toast.error('请先登录')
|
||||||
return false
|
return
|
||||||
}
|
|
||||||
if (reset) {
|
|
||||||
notifications.value = []
|
|
||||||
page.value = 0
|
|
||||||
currentUnread.value = unread
|
|
||||||
}
|
}
|
||||||
isLoadingMessage.value = true
|
isLoadingMessage.value = true
|
||||||
const endpoint = currentUnread.value
|
notifications.value = []
|
||||||
? `/api/notifications/unread?page=${page.value}`
|
const res = await fetch(`${API_BASE_URL}/api/notifications`, {
|
||||||
: `/api/notifications?page=${page.value}`
|
|
||||||
const res = await fetch(`${API_BASE_URL}${endpoint}`, {
|
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${token}`,
|
Authorization: `Bearer ${token}`,
|
||||||
},
|
},
|
||||||
@@ -147,7 +138,7 @@ function createFetchNotifications() {
|
|||||||
isLoadingMessage.value = false
|
isLoadingMessage.value = false
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
toast.error('获取通知失败')
|
toast.error('获取通知失败')
|
||||||
return true
|
return
|
||||||
}
|
}
|
||||||
const data = await res.json()
|
const data = await res.json()
|
||||||
|
|
||||||
@@ -293,14 +284,10 @@ function createFetchNotifications() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
page.value++
|
|
||||||
return data.length < 50
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e)
|
console.error(e)
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const markRead = async (id) => {
|
const markRead = async (id) => {
|
||||||
@@ -348,6 +335,7 @@ function createFetchNotifications() {
|
|||||||
markRead,
|
markRead,
|
||||||
notifications,
|
notifications,
|
||||||
isLoadingMessage,
|
isLoadingMessage,
|
||||||
|
markRead,
|
||||||
markAllRead,
|
markAllRead,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user