source: chapterx-frontend/src/store/notificationStore.ts@ e882b92

main
Last change on this file since e882b92 was e882b92, checked in by kikisrbinoska <srbinoskakristina07@…>, 13 days ago

Added corrected entitef from the ER diagram and changes for the logic to be coresponding to the ddl

  • Property mode set to 100644
File size: 2.5 KB
Line 
1import { create } from 'zustand'
2import axios from 'axios'
3import { Notification } from '../types'
4
5const API = 'https://localhost:7125/api'
6
7function getAuthHeaders() {
8 try {
9 const token = JSON.parse(localStorage.getItem('chapterx-auth') || '{}')?.state?.token
10 return token ? { Authorization: `Bearer ${token}` } : {}
11 } catch {
12 return {}
13 }
14}
15
16interface NotificationStore {
17 notifications: Notification[]
18 fetchUserNotifications: (userId: number) => Promise<void>
19 addNotification: (n: { userId: number; contentType: string; content: string; storyId?: number; link?: string }) => Promise<void>
20 markAllRead: () => Promise<void>
21 markRead: (id: number) => Promise<void>
22 getUnreadCount: () => number
23}
24
25export const useNotificationStore = create<NotificationStore>((set, get) => ({
26 notifications: [],
27
28 fetchUserNotifications: async (userId) => {
29 try {
30 const res = await axios.get(`${API}/notifications/user/${userId}`, { headers: getAuthHeaders() })
31 const data: any[] = res.data ?? []
32 const notifications: Notification[] = data.map(n => ({
33 notification_id: n.id,
34 user_id: userId,
35 type: n.contentType ?? 'info',
36 title: n.contentType ?? 'Notification',
37 message: n.content,
38 link: n.link,
39 is_read: n.isRead,
40 created_at: n.createdAt,
41 }))
42 set({ notifications })
43 } catch {
44 // keep existing
45 }
46 },
47
48 addNotification: async ({ userId, contentType, content, storyId, link }) => {
49 try {
50 await axios.post(`${API}/notifications`, {
51 content,
52 contentType,
53 userId,
54 storyId,
55 link,
56 }, { headers: getAuthHeaders() })
57 } catch {
58 // silent — notification is for recipient, not current user
59 }
60 },
61
62 markAllRead: async () => {
63 const unread = get().notifications.filter(n => !n.is_read)
64 set(state => ({ notifications: state.notifications.map(n => ({ ...n, is_read: true })) }))
65 try {
66 await Promise.all(unread.map(n =>
67 axios.put(`${API}/notifications/${n.notification_id}/read`, {}, { headers: getAuthHeaders() })
68 ))
69 } catch {
70 // keep optimistic
71 }
72 },
73
74 markRead: async (id) => {
75 set(state => ({
76 notifications: state.notifications.map(n =>
77 n.notification_id === id ? { ...n, is_read: true } : n
78 ),
79 }))
80 try {
81 await axios.put(`${API}/notifications/${id}/read`, {}, { headers: getAuthHeaders() })
82 } catch {
83 // keep optimistic
84 }
85 },
86
87 getUnreadCount: () => get().notifications.filter(n => !n.is_read).length,
88}))
Note: See TracBrowser for help on using the repository browser.