All files / api log.ts

100% Statements 20/20
71.42% Branches 10/14
100% Functions 5/5
100% Lines 18/18

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    1x             1x       4x   4x 3x   3x 1x                       2x 1x     3x 1x 2x   1x 3x 3x                     1x                     2x 2x      
import { AISuggestion, ProgressData } from "./types/suggestion";
import { Log } from "./types/event";
import { LOG_ENDPOINT } from "./endpoints";
 
/**
 * Fetches logs for a given user ID.
 * @param {string} userId 
 * @returns {Promise<{ progressData?: ProgressData; error?: string }>} - The response from the server or an error message.
 */
export async function fetchLogs(userId: string): Promise<{ 
  progressData?: ProgressData;
  error?: string;
}> {
  try {
 
    const response = await fetch(`${LOG_ENDPOINT}/${userId}`);
    const data = await response.json();
  
    if (!data.data) {
      return {
        progressData: {
          suggestions: [],
          progress: {
            totalAccepted: 0,
            totalWithBugs: 0,
            percentageWithBugs: 0
          }
        }
      }
    }
  
    if (!Array.isArray(data.data)) {
      throw new Error("Invalid logs data format");
    }
  
    const acceptedLogs = data.data.filter((log: Log) => log.event === "USER_ACCEPT");
    const totalAccepted = acceptedLogs.length;
    const totalWithBugs = acceptedLogs.filter((log: Log) => log.metadata?.has_bug).length;
  
    const suggestions: AISuggestion[] = data.data
      .filter((item: Log) => item.metadata?.has_bug !== undefined)
      .map((item: Log) => ({
        hasBug: item.metadata.has_bug,
        suggestionText: item.metadata.suggestion_text,
        id: item.id.toString(),
        created_at: item.timestamp,
        model: item.metadata.model,
        prompt: item.metadata.prompt,
        timeLapsed: item.time_lapse,
        accepted: item.event === "USER_ACCEPT",
      }));
  
    return {
      progressData: {
        suggestions,
        progress: {
          totalAccepted,
          totalWithBugs,
          percentageWithBugs: totalAccepted > 0 ? (totalWithBugs / totalAccepted) * 100 : 0,
        },
      }
    };
  } catch(error){
    console.error("Error fetching logs:", error);
    return { error: error instanceof Error ? error.message : "Unknown error occurred" };
  }
}