Retrieves recent listening sessions

Fetches and formats information about the most recent listening sessions, providing a chronological view of the user's listening behavior. Sessions represent continuous periods of listening activity separated by significant time gaps.

The returned data includes:

  • Session identifier and start timestamp
  • Duration of the session in minutes
  • Number of tracks played during the session
  • Skip count and calculated skip percentage

This function is primarily used for dashboard visualizations and reports that show patterns in listening duration and engagement over time. Results are sorted by recency with the most recent sessions first.

// Display the last 5 listening sessions
const recentSessions = await getRecentSessions(5);
renderSessionHistoryChart(recentSessions);
export const getRecentSessions = async (
limit: number = 3,
): Promise<
Array<{
id: string;
date: string;
duration: number;
trackCount: number;
skipCount: number;
skipPercentage: number;
}>
> => {
try {
const statistics = await getStatistics();

// Convert sessions to the format needed for the dashboard
const sessions = statistics.sessions
.map((session) => ({
id: session.id,
date: session.startTime,
duration: Math.round(session.durationMs / 60000), // Convert to minutes
trackCount: session.trackIds.length,
skipCount: session.skippedTracks,
skipPercentage:
session.trackIds.length > 0
? Math.round(
(session.skippedTracks / session.trackIds.length) * 100,
)
: 0,
}))
.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()) // Sort by most recent
.slice(0, limit);

return sessions;
} catch (error) {
console.error("Error getting recent sessions:", error);
return [];
}
};
  • Parameters

    • limit: number = 3

      Maximum number of sessions to return (default: 3)

    Returns Promise<
        {
            id: string;
            date: string;
            duration: number;
            trackCount: number;
            skipCount: number;
            skipPercentage: number;
        }[],
    >

    Promise resolving to an array of recent listening session objects