Database Advanced Usage

The DB object provides asynchronous access to the game's data. Using modern async/await syntax with try/catch is the recommended way to handle database queries, preventing "callback hell" and silent failures.

Life Hack: Destructuring Daily Leaderboards

When building custom leaderboards or fetching daily scores, you can use ES6 object destructuring to safely map your results directly to variables. Always wrap database calls in a try/catch block to handle scenarios where the database might be temporarily unreachable or the data is missing.

/**
 * Fetches and displays the top killer for the current day.
 * Trigger this from a script NPC or player command.
 */
async function showDailyTopKillers(player) {
    try {
        // Fetch the daily leaderboard for kills using await
        const scores = await DB.getscore('kills', 'daily');

        // Always guard against empty arrays or null returns
        if (!scores || scores.length === 0) {
            player.chat = 'No kills recorded today yet!';
            return;
        }

        // Destructure the top player's data directly
        const { name, score } = scores[0];

        player.showmessage(`Top Killer Today: ${name} with ${score} kills!`);
        player.chat = 'Watch out for them...';
    } catch (error) {
        // Fallback if the database query fails
        player.chat = 'Unable to load scores right now.';
        echo(`[Score System] Failed to load scores: ${error.message}`);
    }
}

Retrieving Player Published Stories (Videos)

You can easily query a player's published stories (replays/videos) using the loadplayerstories method.

/**
 * Loads and plays a random public story from the target player.
 */
async function playRandomPlayerStory(player, targetUserId) {
    try {
        // Fetch only public stories
        const stories = await DB.loadplayerstories(targetUserId, true);

        if (!stories || stories.length === 0) {
            player.showmessage('This player has no public stories.');
            return;
        }

        // Pick a random story
        const randomStory = stories[Math.floor(Math.random() * stories.length)];

        // Play the story to the player
        player.setstory(randomStory.id, { loop: false, freeze: true });

    } catch (error) {
        echo(`[Story System] Error loading stories for ${targetUserId}: ${error.message}`);
    }
}