async function getScoreboard()

in backend/Functions/HTTP/leaderboard_get/app.js [30:81]


async function getScoreboard(gameId, playerId) {
  let scoreboardData;
  const scoreboard = [];
  let includesPlayer = false;
  const queryparms = {
    TableName: scoresTableName,
    IndexName: 'GameScore',
    ExpressionAttributeValues: { ':v1': gameId, ':v2': -1 },
    ExpressionAttributeNames: { '#key': 'gameId', '#score': 'score' },
    KeyConditionExpression: '#key = :v1 AND #score > :v2',
    ProjectionExpression: 'gameId, quizName, playerName, score',
    Limit: 10,
    ScanIndexForward: false,
  };
  try {
    scoreboardData = await ddb.query(queryparms).promise();
  } catch (e) {
    console.error(`could not get leaderboard info ${JSON.stringify(e.stack)}`);
    return { statusCode: 500, body: 'Could not retrieve leaderboard' };
  }
  const leaders = scoreboardData.Count;
  for (let i = 0; i < leaders; i += 1) {
    const playerData = scoreboardData.Items[i];
    const thisScore = (Number(playerData.score) * 100).toFixed(2);
    scoreboard.push({
      Position: i + 1,
      playerName: playerData.playerName,
      Score: `${String(thisScore)}%`,
      playerAvatar: `https://${domain}/${playerData.playerName}/current/thumb.jpg`
    });
    if (playerData.playerName === playerId) {
      includesPlayer = true;
    }
  }
  if (!includesPlayer && playerId !== '') {
    // list does not contain current player'
    const Key = { gameId, playerName: playerId };
    const playerResult = await ddb.get({
      TableName: scoresTableName,
      Key,
    }).promise();
    if (Object.prototype.hasOwnProperty.call(playerResult, 'Item')) {
      scoreboard.push({
        Position: 'unknown',
        playerName: playerResult.Item.playerName,
        Score: `${String(Number(playerResult.Item.score) * 100)}%`,
        playerAvatar: `${domain}$/{playerResult.Item.playerName}/current/thumb.jpg`
      });
    }
  }
  return scoreboard;
}