1

So basically im working on a cron job in my app that fires every 3 hours and updating users 'score' by calling the RiotApi

basically the function so far

exports.updatePlayersPoints = async () => {
  console.log('STARTED UPDATING');
  try {
    const players = await UserLadder.findAll();

    await Promise.all(
      players.map(async (player) => {
        const p = await RiotAccount.findOne({
          where: {
            userId: player.userId,
          },
          include: RiotRegions,
        });

        const beginTime = new Date(player.dataValues.createdAt);

        let data;

        try {
          const res = await axios.get(
            `https://${
              p.dataValues.riot_region.dataValues.name
            }.api.riotgames.com/lol/match/v4/matchlists/by-account/${
              p.dataValues.accountId
            }?queue=420&beginTime=${beginTime.getTime()}&api_key=${
              process.env.RIOT_KEY
            }`
          );

          data = res.data;
        } catch (error) {
          if (!error.response.status === 404) {
            console.error(error);
          }
        }

        if (!data) {
          return;
        }

        let totalScore = player.dataValues.userPoints;

        await Promise.all(
          data.matches.map(async (match, i) => {
            if (i < 15) {
              const { data } = await axios.get(
                `https://${p.dataValues.riot_region.dataValues.name}.api.riotgames.com/lol/match/v4/matches/${match.gameId}?api_key=${process.env.RIOT_KEY}`
              );

              const calculateScore = () => {
                return new Promise((resolve) => {
                  const { stats } = _.find(
                    data.participants,
                    (o) => o.championId === match.champion
                  );

                  const killsPts = stats.kills * 2;
                  const deathPts = stats.deaths * -1.5;
                  const assistsPts = stats.assists;
                  const wardsPts = stats.wardsPlaced / 4;
                  const firstBloodPts = stats.firstBloodKill ? 3 : 0;
                  const firstBloodAssistPts = stats.firstBloodAssist ? 3 : 0;
                  const firstTowerPts = stats.firstTowerKill ? 2 : 0;
                  const firstTowerAssistPts = stats.firstTowerAssist ? 2 : 0;

                  const score =
                    killsPts +
                    deathPts +
                    assistsPts +
                    wardsPts +
                    firstBloodPts +
                    firstBloodAssistPts +
                    firstTowerPts +
                    firstTowerAssistPts;

                  totalScore += score;

                  resolve();
                });
              };

              await calculateScore();
            }
          })
        );

        const user = await UserLadder.findOne({
          where: {
            userId: player.userId,
          },
        });

        user.userPoints = parseFloat(totalScore);
        user.lastGameId = data.matches[0].gameId;

        await user.save();
      })
    );
    console.log('FINISHED UPDATING');
  } catch (error) {
    console.error(error);
  }
};

Basically it just looks up the table userladder to find the players that are signed to the ladder and for each one of these players it fires a map function that makes a request to the riotapi to get the match history of this player and then later make an inside map function to map each one of these matches.

but basically I updated it to now keep track of the game id of the last call before 3 hours so it doesn't have to make request that was already done.

user.lastGameId = data.matches[0].gameId;

but now in my second map function that maps the matches I wasn't it so that if the last game from my database matches the game id that currently being mapped I want to stop the map function and not continue this record or the ones after because it also means they all have been already counted.

but I can not seem to find a way to do it.

i tried using break; but it didn't work

any ideas?

using for loop

I tried a small test with for loop so I tried

    for (let i = 0; i < 15; i++) {
      await new Promise(async (resolve, reject) => {
        const match = data.matches[i];
        console.log(match);
        resolve();
        if (i === 1) {
          break;
        }
      });
    }

but I still go the same error

SyntaxError: Illegal break statement

A. Atiyah
  • 515
  • 1
  • 6
  • 16
  • 2
    When I google "javascript break a map function", I get this stackoverflow question. Will this serve your use case? https://stackoverflow.com/questions/12260529/break-statement-in-javascript-array-map-method – Jamie Jul 07 '20 at 20:31
  • @Jamie I saw it, i tried it and got an 'illegal break' error, hold on ill edit the question with the code – A. Atiyah Jul 07 '20 at 20:32
  • @Jamine just updated it, lmk if it helped – A. Atiyah Jul 07 '20 at 20:34

1 Answers1

1

Instead of trying to "break" a map, you should filter the matches that you want to process before you execute the map.

Something like this:

await Promise.all(
  const filteredMatches = data.matches.filter(match => match.gameId > previousId);
  filteredMatches.map(async (match, i) => { ...

More on filter() in javascript.

Edit: If generated id's are random and are not ordered, you can store all previous id's in a Set, and then just ask if it has been previously added

await Promise.all(
      const filteredMatches = data.matches.filter(match => mySet.has(match.gameId));
      filteredMatches.map(async (match, i) => { ...

More on Set in javascript.

Codigo Morsa
  • 820
  • 7
  • 14
  • I thought about doing this but the thing is the ids coming back are actually random, so match.gameId > previously won't work, what I need to do is completely stop it when it hits the previously so it doesn't continue it or anything after it. sorry for late response. :) – A. Atiyah Jul 08 '20 at 12:29
  • I reallized that it may be neccesary to add a ! like !mySet.has(match.gameId) in order to filter only those we have not processed before, It has doing it the opposite way. – Codigo Morsa Jul 08 '20 at 19:04