All files / src/hooks useNotifications.ts

23.76% Statements 48/202
100% Branches 0/0
0% Functions 0/1
23.76% Lines 48/202

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 2031x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                     1x 1x  
'use client';
 
import { useState, useEffect, useCallback, useRef } from 'react';
import { useSession } from 'next-auth/react';
import type { NotificationPayload, NotificationsResponse } from '@/lib/notifications/types';
 
interface UseNotificationsOptions {
  /** Polling interval in milliseconds (0 to disable) */
  pollingInterval?: number;
  /** Whether to auto-fetch on mount */
  autoFetch?: boolean;
  /** Maximum number of notifications to fetch */
  limit?: number;
}
 
interface UseNotificationsReturn {
  /** List of notifications */
  notifications: NotificationPayload[];
  /** Count of unread notifications */
  unreadCount: number;
  /** Whether notifications are loading */
  isLoading: boolean;
  /** Error message if any */
  error: string | null;
  /** Whether the hook is connected/active */
  isActive: boolean;
  /** Fetch/refresh notifications */
  refresh: () => Promise<void>;
  /** Mark a notification as read */
  markAsRead: (id: string) => Promise<void>;
  /** Mark all notifications as read */
  markAllAsRead: () => Promise<void>;
}
 
/**
 * Hook for managing user notifications
 *
 * Provides real-time notification updates using polling with optimistic updates.
 *
 * @example
 * ```tsx
 * const { notifications, unreadCount, markAsRead } = useNotifications({
 *   pollingInterval: 30000, // Poll every 30 seconds
 * });
 * ```
 */
export function useNotifications(
  options: UseNotificationsOptions = {}
): UseNotificationsReturn {
  const { pollingInterval = 30000, autoFetch = true, limit = 20 } = options;
  const { data: session, status } = useSession();

  const [notifications, setNotifications] = useState<NotificationPayload[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const pollingRef = useRef<NodeJS.Timeout | null>(null);
  const isAuthenticated = status === 'authenticated' && !!session?.user;

  /**
   * Fetch notifications from the API
   */
  const fetchNotifications = useCallback(async () => {
    if (!isAuthenticated) return;

    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(`/api/notifications?limit=${limit}`);

      if (!response.ok) {
        throw new Error('Failed to fetch notifications');
      }

      const data: NotificationsResponse = await response.json();

      setNotifications(
        data.notifications.map((n) => ({
          id: n.id,
          type: n.type as NotificationPayload['type'],
          title: n.title,
          message: n.message,
          link: n.link || undefined,
          read: n.read,
          createdAt: new Date(n.createdAt).toISOString(),
        }))
      );
      setUnreadCount(data.unreadCount);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setIsLoading(false);
    }
  }, [isAuthenticated, limit]);

  /**
   * Mark a notification as read
   */
  const markAsRead = useCallback(
    async (id: string) => {
      if (!isAuthenticated) return;

      // Optimistic update
      setNotifications((prev) =>
        prev.map((n) => (n.id === id ? { ...n, read: true } : n))
      );
      setUnreadCount((prev) => Math.max(0, prev - 1));

      try {
        const response = await fetch(`/api/notifications/${id}/read`, {
          method: 'POST',
        });

        if (!response.ok) {
          throw new Error('Failed to mark notification as read');
        }
      } catch (err) {
        // Revert on error
        setNotifications((prev) =>
          prev.map((n) => (n.id === id ? { ...n, read: false } : n))
        );
        setUnreadCount((prev) => prev + 1);
        setError(err instanceof Error ? err.message : 'Unknown error');
      }
    },
    [isAuthenticated]
  );

  /**
   * Mark all notifications as read
   */
  const markAllAsRead = useCallback(async () => {
    if (!isAuthenticated) return;

    // Optimistic update
    const previousNotifications = [...notifications];
    const previousUnreadCount = unreadCount;

    setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
    setUnreadCount(0);

    try {
      const response = await fetch('/api/notifications/read-all', {
        method: 'POST',
      });

      if (!response.ok) {
        throw new Error('Failed to mark all as read');
      }
    } catch (err) {
      // Revert on error
      setNotifications(previousNotifications);
      setUnreadCount(previousUnreadCount);
      setError(err instanceof Error ? err.message : 'Unknown error');
    }
  }, [isAuthenticated, notifications, unreadCount]);

  // Initial fetch
  useEffect(() => {
    if (autoFetch && isAuthenticated) {
      fetchNotifications();
    }
  }, [autoFetch, isAuthenticated, fetchNotifications]);

  // Polling
  useEffect(() => {
    if (!isAuthenticated || pollingInterval <= 0) return;

    pollingRef.current = setInterval(fetchNotifications, pollingInterval);

    return () => {
      if (pollingRef.current) {
        clearInterval(pollingRef.current);
        pollingRef.current = null;
      }
    };
  }, [isAuthenticated, pollingInterval, fetchNotifications]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      if (pollingRef.current) {
        clearInterval(pollingRef.current);
      }
    };
  }, []);

  return {
    notifications,
    unreadCount,
    isLoading,
    error,
    isActive: isAuthenticated,
    refresh: fetchNotifications,
    markAsRead,
    markAllAsRead,
  };
}
 
export default useNotifications;