All files / src/features/setting/services profile.service.ts

100% Statements 33/33
82.5% Branches 33/40
100% Functions 3/3
100% Lines 33/33

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                                                                                    20x   6x 2x     4x 4x   3x                 8x   8x 1x     7x 7x     5x     5x                   5x   5x   2x                     10x   10x 2x     8x 8x   8x     8x                     7x 3x 3x             4x     4x 3x 3x         4x   4x                   6x  
import { authService } from '@/features/auth/services/auth.service';
import { apiClient } from '@/lib/http-client';
import { useUserStore } from '@/store/user-store';
import { API_ENDPOINTS, SERVICE_ERRORS } from '@/constants/setting';
 
export interface AvatarData {
  id: number;
  url: string;
  name: string;
  formats?: {
    thumbnail?: { url: string };
    small?: { url: string };
    medium?: { url: string };
    large?: { url: string };
  };
  [key: string]: any;
}
 
export interface ProfileData {
  id: number;
  username: string;
  email: string;
  name?: string;
  phone?: string;
  nationality?: string;
  avatar?: string | AvatarData;
  confirmed: boolean;
  blocked: boolean;
  createdAt: string;
  updatedAt: string;
}
 
export interface UpdateProfileData {
  username?: string;
  // email?: string; // Email updates not allowed for security reasons
  name?: string;
  phone?: string;
  nationality?: string;
}
 
class ProfileService {
  async getProfile(): Promise<ProfileData> {
    const token = authService.getAuthToken();
 
    if (!token) {
      throw new Error(SERVICE_ERRORS.COMMON.UNAUTHENTICATED);
    }
 
    try {
      return await apiClient.get(API_ENDPOINTS.PROFILE);
    } catch (error: any) {
      throw new Error(
        error?.response?.data?.error?.message ||
          error?.response?.data?.message ||
          SERVICE_ERRORS.PROFILE.FETCH_FAILED
      );
    }
  }
 
  async updateProfile(data: UpdateProfileData): Promise<ProfileData> {
    const token = authService.getAuthToken();
 
    if (!token) {
      throw new Error(SERVICE_ERRORS.COMMON.UNAUTHENTICATED);
    }
 
    try {
      const updatedProfile = await apiClient.put(API_ENDPOINTS.PROFILE, data);
 
      // Update user profile in Zustand store with proper data mapping
      const { updateProfile: updateCurrentProfile } = useUserStore.getState();
 
      // Map the API response to UserProfile format
      const userProfileUpdate = {
        id: updatedProfile.id?.toString() || '',
        name: updatedProfile.name || updatedProfile.username || '',
        email: updatedProfile.email || '',
        phone: updatedProfile.phone || '',
        nationality: updatedProfile.nationality || '',
        username: updatedProfile.username || '',
        avatar: updatedProfile.avatar || null,
      };
 
      updateCurrentProfile(userProfileUpdate);
 
      return updatedProfile;
    } catch (error: any) {
      throw new Error(
        error?.response?.data?.error?.message ||
          error?.response?.data?.message ||
          SERVICE_ERRORS.PROFILE.UPDATE_FAILED
      );
    }
  }
 
  async uploadAvatar(
    file: File
  ): Promise<{ message: string; avatar?: AvatarData }> {
    const token = authService.getAuthToken();
 
    if (!token) {
      throw new Error(SERVICE_ERRORS.COMMON.UNAUTHENTICATED);
    }
 
    const formData = new FormData();
    formData.append('avatar', file);
 
    try {
      // For file uploads, we need to use the base httpClient to get the full response
      // and set the proper headers
      const response = await fetch(
        `${import.meta.env.VITE_API_URL}${API_ENDPOINTS.PROFILE_AVATAR}`,
        {
          method: 'POST',
          headers: {
            Authorization: `Bearer ${token}`,
          },
          body: formData,
        }
      );
 
      if (!response.ok) {
        const error = await response.json();
        throw new Error(
          error.error?.message ||
            error.message ||
            SERVICE_ERRORS.PROFILE.AVATAR_UPLOAD_FAILED
        );
      }
 
      const result = await response.json();
 
      // Update user profile in Zustand store with the new avatar
      if (result.avatar) {
        const { updateProfile: updateCurrentProfile } = useUserStore.getState();
        updateCurrentProfile({
          avatar: result.avatar.url || result.avatar,
        });
      }
 
      return result;
    } catch (error: any) {
      throw new Error(
        error?.response?.data?.error?.message ||
          error?.response?.data?.message ||
          error?.message ||
          SERVICE_ERRORS.PROFILE.AVATAR_UPLOAD_FAILED
      );
    }
  }
}
 
export const profileService = new ProfileService();