refactor: clean code of the Transformers

This commit is contained in:
Valentin Kaelin 2019-11-16 17:43:55 +01:00
parent b3bedb378a
commit a200da1a05
6 changed files with 98 additions and 107 deletions

View file

@ -40,19 +40,7 @@ class MatchController {
let matchFromRiot = await Jax.Match.get(gameId) let matchFromRiot = await Jax.Match.get(gameId)
const champions = await Jax.DDragon.Champion.list() matchFromRiot = await DetailedMatchTransformer.transform(matchFromRiot)
const items = await Jax.DDragon.Item.list()
const runes = await Jax.DDragon.Rune.list()
const version = Jax.DDragon.Version
const ctx = {
champions: champions.data,
items: items.data,
runes,
version,
MatchHelper
}
matchFromRiot = DetailedMatchTransformer.transform(matchFromRiot, ctx)
// DetailedMatch.save(matchFromRiot) // DetailedMatch.save(matchFromRiot)

View file

@ -101,24 +101,12 @@ class MatchHelper {
/* If we have to store some matches in the db */ /* If we have to store some matches in the db */
if (matchesFromApi.length !== 0) { if (matchesFromApi.length !== 0) {
const items = await Jax.DDragon.Item.list()
const champions = await Jax.DDragon.Champion.list()
const runes = await Jax.DDragon.Rune.list()
const version = Jax.DDragon.Version
const ctx = { const ctx = {
account, account,
champions: champions.data,
items: items.data,
runes,
version,
MatchHelper: this MatchHelper: this
} }
// Transform raw matches data
matchesFromApi = matchesFromApi.map(m => { await BasicMatchTransformer.transform(matchesFromApi, ctx)
if (m) return BasicMatchTransformer.transform(m, ctx)
})
console.log(matchesFromApi.length)
Logger.transport('file').info(matchesFromApi) Logger.transport('file').info(matchesFromApi)
matchesDetails = [...matchesDetails, ...matchesFromApi] matchesDetails = [...matchesDetails, ...matchesFromApi]
@ -136,37 +124,6 @@ class MatchHelper {
return matchesDetails return matchesDetails
} }
/**
* Return the lane of the summoner according to timeline
* @param timeline from Riot Api
*/
getRoleName(timeline) {
if (timeline.lane === 'BOTTOM' && timeline.role.includes('SUPPORT')) {
return 'SUPPORT'
}
return timeline.lane
}
/**
* Return time in a formatted way
* @param sec time in seconds to convert
*/
secToTime(sec) {
const min = Math.floor(sec / 60)
const newSec = sec - min * 60
return min + 'm' + (newSec < 10 ? '0' + newSec : newSec) + 's'
}
/**
* Sort array of Roles according to a specific order
* @param a first role
* @param b second role
*/
sortTeamByRole(a, b) {
const sortingArr = ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'SUPPORT']
return sortingArr.indexOf(a.role) - sortingArr.indexOf(b.role)
}
} }
module.exports = new MatchHelper() module.exports = new MatchHelper()

View file

@ -30,11 +30,21 @@ class StatsHelper {
return { return {
global: globalStats[0], global: globalStats[0],
league: gamemodeStats, league: gamemodeStats,
role: roleStats.sort(MatchHelper.sortTeamByRole), role: roleStats.sort(this.sortTeamByRole),
class: championClassStats, class: championClassStats,
mates, mates,
} }
} }
/**
* Sort array of Roles according to a specific order
* @param a first role
* @param b second role
*/
sortTeamByRole(a, b) {
const sortingArr = ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'SUPPORT']
return sortingArr.indexOf(a.role) - sortingArr.indexOf(b.role)
}
} }
module.exports = new StatsHelper() module.exports = new StatsHelper()

View file

@ -10,19 +10,27 @@ const MatchTransformer = use('App/Transformers/MatchTransformer')
class BasicMatchTransformer extends MatchTransformer { class BasicMatchTransformer extends MatchTransformer {
/** /**
* Transform raw data from Riot API * Transform raw data from Riot API
* @param match data from Riot API * @param matches data from Riot API, Array of match or a single match
* @param ctx context * @param ctx context
*/ */
transform(match, { account, champions, items, runes, version, MatchHelper }) { async transform(matches, { account }) {
this.match = match await super.getContext()
this.champions = champions
this.items = items
this.runes = runes
this.version = version
this.MatchHelper = MatchHelper
if (Array.isArray(matches)) {
matches.forEach((match, index) => {
matches[index] = this.transformOneMatch(match, account)
});
} else {
matches = this.transformOneMatch(matches, account)
}
}
/**
* Transform raw data for 1 match
*/
transformOneMatch(match, account) {
// Global data about the match // Global data about the match
const globalInfos = super.getGameInfos() const globalInfos = super.getGameInfos(match)
const participantId = match.participantIdentities.find((p) => p.player.currentAccountId === account.accountId).participantId const participantId = match.participantIdentities.find((p) => p.player.currentAccountId === account.accountId).participantId
const player = match.participants[participantId - 1] const player = match.participants[participantId - 1]
@ -35,7 +43,7 @@ class BasicMatchTransformer extends MatchTransformer {
} }
// Player data // Player data
const playerData = super.getPlayerData(player, false) const playerData = super.getPlayerData(match, player, false)
// Teams data // Teams data
const allyTeam = [] const allyTeam = []
@ -44,8 +52,8 @@ class BasicMatchTransformer extends MatchTransformer {
const allData = match.participants[summoner.participantId - 1] const allData = match.participants[summoner.participantId - 1]
const playerInfos = { const playerInfos = {
name: summoner.player.summonerName, name: summoner.player.summonerName,
role: MatchHelper.getRoleName(allData.timeline), role: super.getRoleName(allData.timeline),
champion: (({ id, name }) => ({ id, name }))(Object.entries(champions).find(([, champion]) => Number(champion.key) === allData.championId)[1]) champion: (({ id, name }) => ({ id, name }))(Object.entries(this.champions).find(([, champion]) => Number(champion.key) === allData.championId)[1])
} }
if (allData.teamId === player.teamId) { if (allData.teamId === player.teamId) {
@ -54,8 +62,8 @@ class BasicMatchTransformer extends MatchTransformer {
enemyTeam.push(playerInfos) enemyTeam.push(playerInfos)
} }
} }
allyTeam.sort(MatchHelper.sortTeamByRole) allyTeam.sort(super.sortTeamByRole)
enemyTeam.sort(MatchHelper.sortTeamByRole) enemyTeam.sort(super.sortTeamByRole)
return { return {
summoner_puuid: account.puuid, summoner_puuid: account.puuid,

View file

@ -11,22 +11,16 @@ class DetailedMatchTransformer extends MatchTransformer {
/** /**
* Transform raw data from Riot API * Transform raw data from Riot API
* @param match data from Riot API * @param match data from Riot API
* @param ctx context
*/ */
transform(match, { champions, items, runes, version, MatchHelper }) { async transform(match) {
this.match = match await super.getContext()
this.champions = champions
this.items = items
this.runes = runes
this.version = version
this.MatchHelper = MatchHelper
// Global data // Global data
const globalInfos = super.getGameInfos() const globalInfos = super.getGameInfos(match)
// Teams // Teams
const firstTeam = this.getTeamData(match.teams[0]) const firstTeam = this.getTeamData(match, match.teams[0])
const secondTeam = this.getTeamData(match.teams[1]) const secondTeam = this.getTeamData(match, match.teams[1])
return { return {
gameId: match.gameId, gameId: match.gameId,
@ -39,16 +33,17 @@ class DetailedMatchTransformer extends MatchTransformer {
/** /**
* Get all data of one team * Get all data of one team
* @param match raw match data from Riot API
* @param team raw team data from Riot API * @param team raw team data from Riot API
*/ */
getTeamData(team) { getTeamData(match, team) {
let win = team.win let win = team.win
if (this.match.gameDuration < 300) { if (match.gameDuration < 300) {
win = 'Remake' win = 'Remake'
} }
// Global stats of the team // Global stats of the team
const teamPlayers = this.match.participants.filter(p => p.teamId === team.teamId) const teamPlayers = match.participants.filter(p => p.teamId === team.teamId)
const teamStats = teamPlayers.reduce((prev, cur) => { const teamStats = teamPlayers.reduce((prev, cur) => {
prev.kills += cur.stats.kills prev.kills += cur.stats.kills
prev.deaths += cur.stats.deaths prev.deaths += cur.stats.deaths
@ -78,8 +73,8 @@ class DetailedMatchTransformer extends MatchTransformer {
// Players // Players
const players = teamPlayers const players = teamPlayers
.map(p => super.getPlayerData(p, true, teamStats)) .map(p => super.getPlayerData(match, p, true, teamStats))
.sort(this.MatchHelper.sortTeamByRole) .sort(super.sortTeamByRole)
return { return {
bans, bans,

View file

@ -1,40 +1,52 @@
'use strict' 'use strict'
const Jax = use('Jax')
/** /**
* MatchTransformer class * MatchTransformer class
* *
* @class MatchTransformer * @class MatchTransformer
*/ */
class MatchTransformer { class MatchTransformer {
/**
* Get global Context with DDragon Data
*/
async getContext() {
const items = await Jax.DDragon.Item.list()
const champions = await Jax.DDragon.Champion.list()
const runes = await Jax.DDragon.Rune.list()
const version = Jax.DDragon.Version
this.champions = champions.data
this.items = items.data
this.runes = runes
this.version = version
}
/** /**
* Get global data about the match * Get global data about the match
*/ */
getGameInfos() { getGameInfos(match) {
const map = this.match.mapId
const gamemode = this.match.queueId
const date = this.match.gameCreation
// const time = this.MatchHelper.secToTime(this.match.gameDuration)
const time = this.match.gameDuration
return { return {
map, map: match.mapId,
gamemode, gamemode: match.queueId,
date, date: match.gameCreation,
time time: match.gameDuration
} }
} }
/** /**
* Get player specific data during the match * Get player specific data during the match
* @param match
* @param player * @param player
* @param detailed : detailed or not stats * @param detailed : detailed or not stats
* @param teamStats : if detailed, the teamStats argument is mandatory * @param teamStats : if detailed, the teamStats argument is mandatory
*/ */
getPlayerData(player, detailed, teamStats = {}) { getPlayerData(match, player, detailed, teamStats = {}) {
const identity = this.match.participantIdentities.find(p => p.participantId === player.participantId) const identity = match.participantIdentities.find(p => p.participantId === player.participantId)
const name = identity.player.summonerName const name = identity.player.summonerName
const champion = (({ id, name, tags }) => ({ id, name, tags }))(Object.entries(this.champions).find(([, champion]) => Number(champion.key) === player.championId)[1]) const champion = (({ id, name, tags }) => ({ id, name, tags }))(Object.entries(this.champions).find(([, champion]) => Number(champion.key) === player.championId)[1])
const role = this.MatchHelper.getRoleName(player.timeline) const role = this.getRoleName(player.timeline)
const level = player.stats.champLevel const level = player.stats.champLevel
// Regular stats / Full match stats // Regular stats / Full match stats
@ -60,8 +72,8 @@ class MatchTransformer {
let percentStats let percentStats
if (detailed) { if (detailed) {
percentStats = { percentStats = {
minions: +(stats.minions / (this.match.gameDuration / 60)).toFixed(2), minions: +(stats.minions / (match.gameDuration / 60)).toFixed(2),
vision: +(stats.vision / (this.match.gameDuration / 60)).toFixed(2), vision: +(stats.vision / (match.gameDuration / 60)).toFixed(2),
gold: +(player.stats.goldEarned * 100 / teamStats.gold).toFixed(1) + '%', gold: +(player.stats.goldEarned * 100 / teamStats.gold).toFixed(1) + '%',
dmgChamp: +(player.stats.totalDamageDealtToChampions * 100 / teamStats.dmgChamp).toFixed(1) + '%', dmgChamp: +(player.stats.totalDamageDealtToChampions * 100 / teamStats.dmgChamp).toFixed(1) + '%',
dmgObj: +(player.stats.damageDealtToObjectives * 100 / teamStats.dmgObj).toFixed(1) + '%', dmgObj: +(player.stats.damageDealtToObjectives * 100 / teamStats.dmgObj).toFixed(1) + '%',
@ -70,7 +82,7 @@ class MatchTransformer {
stats.kp = teamStats.kills === 0 ? '0%' : +((stats.kills + stats.assists) * 100 / teamStats.kills).toFixed(1) + '%' stats.kp = teamStats.kills === 0 ? '0%' : +((stats.kills + stats.assists) * 100 / teamStats.kills).toFixed(1) + '%'
} else { } else {
const totalKills = this.match.participants.reduce((prev, current) => { const totalKills = match.participants.reduce((prev, current) => {
if (current.teamId !== player.teamId) { if (current.teamId !== player.teamId) {
return prev return prev
} }
@ -128,6 +140,27 @@ class MatchTransformer {
percentStats, percentStats,
} }
} }
/**
* Return the lane of the summoner according to timeline
* @param timeline from Riot Api
*/
getRoleName(timeline) {
if (timeline.lane === 'BOTTOM' && timeline.role.includes('SUPPORT')) {
return 'SUPPORT'
}
return timeline.lane
}
/**
* Sort array of Roles according to a specific order
* @param a first role
* @param b second role
*/
sortTeamByRole(a, b) {
const sortingArr = ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'SUPPORT']
return sortingArr.indexOf(a.role) - sortingArr.indexOf(b.role)
}
} }
module.exports = MatchTransformer module.exports = MatchTransformer