Saves statistics data to persistent storage

Writes the complete statistics data structure to a JSON file in the application's user data directory. The function handles proper serialization of complex data structures (like Sets) and updates the lastUpdated timestamp.

The function performs several important operations:

  • Ensures the data directory exists before attempting to write
  • Updates the lastUpdated timestamp to the current time
  • Converts Set objects to arrays for proper JSON serialization
  • Formats JSON with proper indentation for readability
  • Handles error conditions gracefully
// Update and save statistics after processing a skipped track
const stats = await getStatistics();
stats.totalSkips++;
stats.overallSkipRate = stats.totalSkips / stats.totalPlays;
await saveStatistics(stats);
export const saveStatistics = async (
statistics: StatisticsData,
): Promise<boolean> => {
try {
await ensureDir(join(app.getPath("userData"), "data"));

// Update the lastUpdated timestamp
statistics.lastUpdated = new Date().toISOString();

// Before saving, convert all Set objects to arrays for proper serialization
const preparedStatistics = prepareStatisticsForSave(statistics);

writeJsonSync(statisticsFilePath, preparedStatistics, { spaces: 2 });
return true;
} catch (error) {
console.error("Error saving statistics:", error);
return false;
}
};