All files / src/api user-api.ts

18.51% Statements 10/54
100% Branches 0/0
0% Functions 0/1
18.51% Lines 10/54

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 551x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                          
import { USER_ENDPOINT } from "./types/endpoints";
import { User } from "./types/user";
 
/**
 * Fetches detailed user information by their unique ID.
 *
 * @param userID - The user's unique identifier.
 * @returns An object containing the user data or an error message.
 */
export async function getUserByID(
  userID: string
): Promise<{ user?: User; error?: string }> {
  try {
    const response = await fetch(`${USER_ENDPOINT}/${userID}`, {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    });

    const data = await response.json();

    if (!response.ok) {
      return {
        error:
          data.message ||
          `Failed to get user: ${response.status} ${response.statusText}`,
      };
    }

    if (!data.data) {
      return { error: "Invalid response: Missing user data" };
    }

    const userData = data.data;

    const user: User = {
      id: userData.id,
      email: userData.email,
      first_name: userData.first_name,
      last_name: userData.last_name,
      isLocked: userData.is_locked,
      code_context_id: userData.code_context_id,
      auth_token: userID,
      isAuthenticated: true,
      userStatus: userData.status,
      role: userData.role,
      settings: userData.settings,
    };
    return { user: user };
  } catch (err) {
    return {
      error: err instanceof Error ? err.message : "Unknown error occurred",
    };
  }
}