All files / src/services notificationApiClient.ts

100% Statements 44/44
100% Branches 19/19
100% Functions 8/8
100% Lines 43/43

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                                                  2x                             12x 12x 12x 12x 12x   12x 1x   12x 1x     12x         6x                       6x         6x               3x 3x 3x 3x   3x       2x   1x               2x 2x       1x   1x               3x 3x         2x   1x               2x 2x       1x   1x               3x 3x         2x   1x               11x 9x 9x   9x     2x         2x    
/**
 * Notification API Client
 *
 * Story BAT-7 - Notifications API Consolidation
 *
 * HTTP client for Notification Service APIs (Event Management Service)
 * Features:
 * - Fetch notifications for organizers
 * - Mark notifications as read
 * - Delete notifications
 * - Get unread count
 * - EventBridge-triggered notifications
 */
 
import apiClient from '@/services/api/apiClient';
import { AxiosError } from 'axios';
import type {
  NotificationsResponse,
  NotificationCountResponse,
  NotificationFilters,
  MarkAsReadResponse,
  DeleteNotificationResponse,
} from '@/types/notification';
 
// API base path for notification endpoints
const NOTIFICATION_API_PATH = '/notifications';
 
/**
 * Notification API Client Class
 *
 * Handles all HTTP requests to the Notification APIs
 */
class NotificationApiClient {
  /**
   * Get paginated list of notifications with optional filters
   */
  async getNotifications(
    filters: NotificationFilters,
    pagination: { page?: number; limit?: number } = {}
  ): Promise<NotificationsResponse> {
    try {
      const params = new URLSearchParams();
      params.append('username', filters.username);
      params.append('page', (pagination.page || 1).toString());
      params.append('limit', (pagination.limit || 20).toString());
 
      if (filters.status) {
        params.append('status', filters.status);
      }
      if (filters.eventCode) {
        params.append('eventCode', filters.eventCode);
      }
 
      const response = await apiClient.get<NotificationsResponse>(
        `${NOTIFICATION_API_PATH}?${params.toString()}`
      );
 
      // Enhance notifications with computed properties and UI aliases
      const enhancedData = response.data.data.map((notification) => ({
        ...notification,
        isRead: notification.status === 'READ',
        actionUrl: notification.eventCode
          ? `/organizer/events/${notification.eventCode}`
          : undefined,
        // UI aliases for backward compatibility
        title: notification.subject,
        message: notification.body,
        timestamp: notification.createdAt,
      }));
 
      return {
        ...response.data,
        data: enhancedData,
      };
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * Get unread notification count for user
   */
  async getUnreadCount(username: string): Promise<number> {
    try {
      const params = new URLSearchParams();
      params.append('username', username);
      params.append('status', 'UNREAD'); // In-app notifications have status UNREAD
 
      const response = await apiClient.get<NotificationCountResponse>(
        `${NOTIFICATION_API_PATH}/count?${params.toString()}`
      );
 
      return response.data.count;
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * Mark a single notification as read
   */
  async markAsRead(notificationId: string): Promise<MarkAsReadResponse> {
    try {
      const response = await apiClient.put<MarkAsReadResponse>(
        `${NOTIFICATION_API_PATH}/${notificationId}/read`
      );
 
      return response.data;
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * Mark multiple notifications as read (batch)
   */
  async batchMarkAsRead(notificationIds: string[]): Promise<MarkAsReadResponse> {
    try {
      const response = await apiClient.put<MarkAsReadResponse>(
        `${NOTIFICATION_API_PATH}/batch-read`,
        { notificationIds }
      );
 
      return response.data;
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * Delete a notification
   */
  async deleteNotification(notificationId: string): Promise<DeleteNotificationResponse> {
    try {
      const response = await apiClient.delete<DeleteNotificationResponse>(
        `${NOTIFICATION_API_PATH}/${notificationId}`
      );
 
      return response.data;
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * Delete multiple notifications (batch)
   */
  async batchDelete(notificationIds: string[]): Promise<DeleteNotificationResponse> {
    try {
      const response = await apiClient.delete<DeleteNotificationResponse>(
        `${NOTIFICATION_API_PATH}/batch-delete`,
        { data: { notificationIds } }
      );
 
      return response.data;
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * Transform API errors into user-friendly messages
   */
  private transformError(error: unknown): Error {
    if (error instanceof AxiosError) {
      const message = error.response?.data?.message || error.message;
      const correlationId = error.response?.headers?.['x-correlation-id'];
 
      return new Error(correlationId ? `${message} (Correlation ID: ${correlationId})` : message);
    }
 
    return error instanceof Error ? error : new Error('Unknown error occurred');
  }
}
 
// Export singleton instance
export const notificationApiClient = new NotificationApiClient();
export default notificationApiClient;