Start using Vuex Summoner : messy code

This commit is contained in:
Valentin Kaelin 2019-09-08 22:08:49 +02:00
parent 531587566f
commit 56f78fc8a2
8 changed files with 222 additions and 195 deletions

1
client/.env Normal file
View file

@ -0,0 +1 @@
VUE_APP_PATCH=9.17.1

View file

@ -40,7 +40,9 @@ export default {
props: { props: {
matches: { matches: {
type: Array, type: Array,
required: true default() {
return []
}
} }
}, },
@ -48,7 +50,18 @@ export default {
return { return {
gridDays: [], gridDays: [],
indexFirstMonday: 0, indexFirstMonday: 0,
nbColumns: 15 nbColumns: 15,
options: {
year: 'numeric',
month: '2-digit',
day: 'numeric'
}
}
},
watch: {
matches() {
this.fillGrid()
} }
}, },
@ -62,17 +75,11 @@ export default {
createGrid() { createGrid() {
const nbDaysInGrid = this.nbColumns * 7 const nbDaysInGrid = this.nbColumns * 7
const options = {
year: 'numeric',
month: '2-digit',
day: 'numeric'
}
// Create array with all the days of the Grid // Create array with all the days of the Grid
for (let i = 1; i <= nbDaysInGrid; i++) { for (let i = 1; i <= nbDaysInGrid; i++) {
const day = new Date() const day = new Date()
day.setDate(day.getDate() - nbDaysInGrid + i) day.setDate(day.getDate() - nbDaysInGrid + i)
const formattedDay = day.toLocaleString('fr', options) const formattedDay = day.toLocaleString('fr', this.options)
this.gridDays.push({ this.gridDays.push({
date: formattedDay, date: formattedDay,
@ -82,11 +89,14 @@ export default {
}) })
} }
this.fillGrid()
},
fillGrid() {
// Add all the matches made by the summoner // Add all the matches made by the summoner
for (const key in this.matches) { for (const key in this.matches) {
const match = this.matches[key] const match = this.matches[key]
const matchTime = new Date(match.timestamp) const matchTime = new Date(match.timestamp)
const formattedTime = matchTime.toLocaleString('fr', options) const formattedTime = matchTime.toLocaleString('fr', this.options)
const dayOfTheMatch = this.gridDays.filter( const dayOfTheMatch = this.gridDays.filter(
e => e.date === formattedTime e => e.date === formattedTime
@ -119,4 +129,4 @@ export default {
} }
} }
} }
</script> </script>

View file

@ -17,7 +17,7 @@ Vue.use(VueAxios)
Vue.component('v-icon', Icon) Vue.component('v-icon', Icon)
Vue.component('dot-loader', DotLoader) Vue.component('dot-loader', DotLoader)
Vue.prototype.$patch = '9.17.1' Vue.prototype.$patch = process.env.VUE_APP_PATCH
new Vue({ new Vue({

View file

@ -4,7 +4,7 @@ export const axios = axiosHttp
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest' axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers.common['Content-Type'] = 'application/json' axios.defaults.headers.common['Content-Type'] = 'application/json'
axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? 'http://localhost:5000/' : 'https://api.valentinkaelin.ch/' axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? 'http://localhost:3333/' : 'https://api.valentinkaelin.ch/'
export default { export default {
install (Vue) { install (Vue) {

View file

@ -1,6 +1,8 @@
import Vue from 'vue' import Vue from 'vue'
import Vuex from 'vuex' import Vuex from 'vuex'
import * as ddragon from '@/store/modules/ddragon'
import * as notification from '@/store/modules/notification' import * as notification from '@/store/modules/notification'
import * as summoner from '@/store/modules/summoner'
Vue.use(Vuex) Vue.use(Vuex)
@ -8,7 +10,24 @@ const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({ export default new Vuex.Store({
modules: { modules: {
ddragon,
notification, notification,
summoner
},
state: {
regionsList: {
'br': 'br1',
'eune': 'eun1',
'euw': 'euw1',
'jp': 'jp1',
'kr': 'kr',
'lan': 'la1',
'las': 'la2',
'na': 'na1',
'oce': 'oc1',
'tr': 'tr1',
'ru': 'ru'
}
}, },
strict: debug strict: debug
}) })

View file

@ -0,0 +1,22 @@
import { axios } from '@/plugins/axios'
export const namespaced = true
export const state = {
champions: []
}
export const mutations = {
PUSH_CHAMPIONS(state, champions) {
state.champions = champions
}
}
export const actions = {
async getChampions({ commit }) {
console.log('API CALL FOR CHAMPIONS')
const endpoint = 'Champion'
const resp = await axios(({ url: 'ddragon', data: { endpoint }, method: 'POST' }))
commit('PUSH_CHAMPIONS', resp.data.data)
}
}

View file

@ -0,0 +1,140 @@
import { axios } from '@/plugins/axios'
import { timeDifference, secToTime, getRankImg } from '@/helpers/functions.js'
import { maps, gameModes } from '@/data/data.js'
import summonersJSON from '@/data/summoner.json'
export const namespaced = true
export const state = {
infos: [],
loading: false,
summonerFound: false
}
export const mutations = {
SUMMONER_REQUEST(state) {
state.loading = true
},
SUMMONER_FOUND(state, infos) {
state.summonerFound = true
state.loading = false
state.infos = infos
},
SUMMONER_NOT_FOUND(state) {
state.summonerFound = false
state.loading = false
}
}
export const actions = {
async summonerRequest({ commit, dispatch, rootState }, { summoner, region }) {
console.log(summoner, region)
commit('SUMMONER_REQUEST')
try {
const resp = await axios(({ url: 'api', data: { summoner, region }, method: 'POST' }))
await dispatch('ddragon/getChampions', {}, { root: true })
if (resp.data) {
const infos = createObject(resp.data, rootState.ddragon.champions)
commit('SUMMONER_FOUND', infos)
} else {
commit('SUMMONER_NOT_FOUND')
dispatch('notification/add', {
type: 'error',
message: 'Summoner not found.'
}, { root: true })
console.log('Summoner not found - store')
}
} catch (error) {
commit('SUMMONER_NOT_FOUND')
console.log(error)
}
}
}
function createObject(JSONData, championsInfos) {
console.log('--- ALL INFOS ---')
console.log(JSONData)
const userStats = JSONData.account
const soloQStats = JSONData.soloQ
const matches = JSONData.matchesDetails
const matchesInfos = []
// Loop on all matches
for (let i = 0; i < matches.length; i++) {
const currentMatch = matches[i]
const participantId = currentMatch.participantIdentities.find((p) => p.player.currentAccountId === userStats.accountId).participantId
const teamId = currentMatch.participants[participantId - 1].teamId
const win = currentMatch.teams.find((t) => t.teamId === teamId).win === 'Win'
const map = maps[currentMatch.mapId]
let mode = gameModes[currentMatch.queueId]
if (!mode)
mode = 'Undefined gamemode'
const champion = Object.entries(championsInfos).find(([, champion]) => Number(champion.key) === currentMatch.participants[participantId - 1].championId)[0]
const role = currentMatch.participants[participantId - 1].timeline.lane
const timeAgo = timeDifference(currentMatch.gameCreation)
const time = secToTime(currentMatch.gameDuration)
const kills = currentMatch.participants[participantId - 1].stats.kills
const deaths = currentMatch.participants[participantId - 1].stats.deaths
const assists = currentMatch.participants[participantId - 1].stats.assists
const level = currentMatch.participants[participantId - 1].stats.champLevel
const items = []
for (let i = 0; i < 6; i++) {
const currentItem = 'item' + i
items.push(getItemLink(currentMatch.participants[participantId - 1].stats[currentItem]))
}
const gold = (currentMatch.participants[participantId - 1].stats.goldEarned / 1000).toFixed(1) + 'k'
const minions = currentMatch.participants[participantId - 1].stats.totalMinionsKilled + currentMatch.participants[participantId - 1].stats.neutralMinionsKilled
const firstSum = currentMatch.participants[participantId - 1].spell1Id
const secondSum = currentMatch.participants[participantId - 1].spell2Id
matchesInfos.push({
result: win,
map: map,
gamemode: mode,
champ: champion,
role: role,
date: timeAgo,
time: time,
kills: kills,
deaths: deaths,
assists: assists,
level: level,
items: items,
gold: gold,
minions: minions,
firstSum: getSummonerLink(firstSum),
secondSum: getSummonerLink(secondSum)
})
} // end loop matches
console.log('matches infos just below')
console.log(matchesInfos)
return {
accountId: userStats.accountId,
allMatches: JSONData.allMatches,
matches: matchesInfos,
profileIconId: userStats.profileIconId,
name: userStats.name,
level: userStats.summonerLevel,
rank: soloQStats ? soloQStats.tier + ' ' + soloQStats.rank : 'Joueur non classé',
rankImgLink: getRankImg(soloQStats),
rankedWins: soloQStats ? soloQStats.wins : undefined,
rankedLosses: soloQStats ? soloQStats.losses : undefined
}
}
function getItemLink(id) {
return `url('https://ddragon.leagueoflegends.com/cdn/${process.env.VUE_APP_PATCH}/img/item/${id === 0 ? 3637 : id}.png') no-repeat center center / contain`
}
function getSummonerLink(id) {
const spellName = Object.entries(summonersJSON.data).find(([, spell]) => Number(spell.key) === id)[0]
return `https://ddragon.leagueoflegends.com/cdn/${process.env.VUE_APP_PATCH}/img/spell/${spellName}.png`
}

View file

@ -1,7 +1,5 @@
<template> <template>
<div> <div>
<button @click="resetLocalStorage" class="debug"></button>
<header class="search mb-4 bg-teal-900 text-teal-100"> <header class="search mb-4 bg-teal-900 text-teal-100">
<div class="container mx-auto flex justify-between py-8"> <div class="container mx-auto flex justify-between py-8">
<router-link <router-link
@ -10,16 +8,6 @@
>Accueil</router-link> >Accueil</router-link>
<SearchForm @formSubmit="redirect" /> <SearchForm @formSubmit="redirect" />
<button
v-if="summonerFound"
@click="apiCall"
id="refresh"
class="input btn w-20 rounded-lg ml-2 relative"
:disabled="loading"
>
<v-icon name="sync" class="absolute vertical-center horizontal-center" />
</button>
</div> </div>
</header> </header>
@ -41,7 +29,7 @@
class="player__ratio" class="player__ratio"
>{{ localInfos.rankedWins ? localInfos.rankedWins + ' wins / ' + localInfos.rankedLosses + ' losses' : "Joueur non classé" }}</h3> >{{ localInfos.rankedWins ? localInfos.rankedWins + ' wins / ' + localInfos.rankedLosses + ' losses' : "Joueur non classé" }}</h3>
<RecentActivity v-show="localInfos.allMatches" :matches="localInfos.allMatches" /> <RecentActivity :matches="localInfos.allMatches" />
<ul class="list-matches--debug"> <ul class="list-matches--debug">
<Match <Match
@ -68,12 +56,10 @@
<script> <script>
// import itemsJSON from '@/data/item.json' // import itemsJSON from '@/data/item.json'
import summonersJSON from '@/data/summoner.json' import { mapState, mapActions } from 'vuex'
import RecentActivity from '@/components/RecentActivity.vue' import RecentActivity from '@/components/RecentActivity.vue'
import Match from '@/components/Match.vue' import Match from '@/components/Match.vue'
import SearchForm from '@/components/SearchForm.vue' import SearchForm from '@/components/SearchForm.vue'
import { maps, gameModes } from '@/data/data.js'
import { timeDifference, secToTime, getRankImg } from '@/helpers/functions.js'
export default { export default {
components: { components: {
@ -82,194 +68,43 @@ export default {
SearchForm SearchForm
}, },
data() {
return {
championsInfos: [],
localInfos: {},
summonerFound: false,
loading: false,
regionsList: {
'br': 'br1',
'eune': 'eun1',
'euw': 'euw1',
'jp': 'jp1',
'kr': 'kr',
'lan': 'la1',
'las': 'la2',
'na': 'na1',
'oce': 'oc1',
'tr': 'tr1',
'ru': 'ru'
}
}
},
computed: { computed: {
summoner() { summoner() {
return this.$route.params.name return this.$route.params.name
}, },
region() { region() {
return this.$route.params.region return this.$route.params.region
} },
...mapState({
regionsList: state => state.regionsList,
localInfos: state => state.summoner.infos,
summonerFound: state => state.summoner.summonerFound,
loading: state => state.summoner.loading
})
}, },
watch: { watch: {
$route() { $route() {
console.log('route changed') console.log('route changed')
this.checkLocalStorage() this.apiCall()
} }
}, },
created: function () { // created() {
this.getChampionData() // this.getChampionData()
}, // },
mounted: function () { mounted() {
this.checkLocalStorage() this.apiCall()
}, },
methods: { methods: {
async apiCall() { async apiCall() {
const summoner = this.summoner await this.summonerRequest({ summoner: this.summoner, region: this.region })
const region = this.regionsList[this.region]
this.loading = true
try {
const resp = await this.$axios(({ url: 'api', data: { summoner, region }, method: 'POST' }))
if (resp.data) {
this.summonerFound = true
this.createObject(resp.data)
} else {
this.summonerFound = false
this.loading = false
this.$store.dispatch('notification/add', {
type: 'error',
message: 'Summoner not found.'
})
console.log('Summoner not found')
}
} catch (error) {
this.loading = false
console.log(error)
}
},
checkLocalStorage() {
if (localStorage[`${this.summoner}:${this.region}`]) {
console.log('cached')
this.summonerFound = true
this.localInfos = JSON.parse(localStorage[`${this.summoner}:${this.region}`])
} else {
this.apiCall()
}
},
createObject(JSONData) {
console.time('frontend')
console.log('--- ALL INFOS ---')
console.log(JSONData)
const userStats = JSONData.account
const soloQStats = JSONData.soloQ
const matches = JSONData.matchesDetails
const matchesInfos = []
// Loop on all matches
for (let i = 0; i < matches.length; i++) {
const currentMatch = matches[i]
const participantId = currentMatch.participantIdentities.find((p) => p.player.currentAccountId === userStats.accountId).participantId
const teamId = currentMatch.participants[participantId - 1].teamId
const win = currentMatch.teams.find((t) => t.teamId === teamId).win === 'Win'
const map = maps[currentMatch.mapId]
let mode = gameModes[currentMatch.queueId]
if (!mode)
mode = 'Undefined gamemode'
//console.log(Object.entries(this.championsInfos))
//console.log(this.championsInfos)
const champion = Object.entries(this.championsInfos).find(([, champion]) => Number(champion.key) === currentMatch.participants[participantId - 1].championId)[0]
//const champion = championsId[currentMatch.participants[participantId - 1].championId];
const role = currentMatch.participants[participantId - 1].timeline.lane
const timeAgo = timeDifference(currentMatch.gameCreation)
const time = secToTime(currentMatch.gameDuration)
const kills = currentMatch.participants[participantId - 1].stats.kills
const deaths = currentMatch.participants[participantId - 1].stats.deaths
const assists = currentMatch.participants[participantId - 1].stats.assists
const level = currentMatch.participants[participantId - 1].stats.champLevel
const items = []
for (let i = 0; i < 6; i++) {
const currentItem = 'item' + i
items.push(this.getItemLink(currentMatch.participants[participantId - 1].stats[currentItem]))
}
const gold = (currentMatch.participants[participantId - 1].stats.goldEarned / 1000).toFixed(1) + 'k'
const minions = currentMatch.participants[participantId - 1].stats.totalMinionsKilled + currentMatch.participants[participantId - 1].stats.neutralMinionsKilled
const firstSum = currentMatch.participants[participantId - 1].spell1Id
const secondSum = currentMatch.participants[participantId - 1].spell2Id
matchesInfos.push({
result: win,
map: map,
gamemode: mode,
champ: champion,
role: role,
date: timeAgo,
time: time,
kills: kills,
deaths: deaths,
assists: assists,
level: level,
items: items,
gold: gold,
minions: minions,
firstSum: this.getSummonerLink(firstSum),
secondSum: this.getSummonerLink(secondSum)
})
} // end loop matches
console.log('matches infos just below')
console.log(matchesInfos)
this.localInfos = {
accountId: userStats.accountId,
allMatches: JSONData.allMatches,
matches: matchesInfos,
profileIconId: userStats.profileIconId,
name: userStats.name,
level: userStats.summonerLevel,
rank: soloQStats ? soloQStats.tier + ' ' + soloQStats.rank : 'Joueur non classé',
rankImgLink: getRankImg(soloQStats),
rankedWins: soloQStats ? soloQStats.wins : undefined,
rankedLosses: soloQStats ? soloQStats.losses : undefined
}
console.log('====== Saved infos ======')
console.log(this.localInfos)
localStorage[`${this.summoner}:${this.region}`] = JSON.stringify(this.localInfos)
console.timeEnd('frontend')
this.loading = false
},
async getChampionData() {
console.log('API CALL FOR CHAMPIONS')
const endpoint = 'Champion'
const resp = await this.$axios(({ url: 'ddragon', data: { endpoint }, method: 'POST' }))
this.championsInfos = resp.data.data
},
getItemLink(id) {
return `url('https://ddragon.leagueoflegends.com/cdn/${this.$patch}/img/item/${id === 0 ? 3637 : id}.png') no-repeat center center / contain`
},
getSummonerLink(id) {
const spellName = Object.entries(summonersJSON.data).find(([, spell]) => Number(spell.key) === id)[0]
return `https://ddragon.leagueoflegends.com/cdn/${this.$patch}/img/spell/${spellName}.png`
}, },
redirect(summoner, region) { redirect(summoner, region) {
this.$router.push(`/summoner/${region}/${summoner}`) this.$router.push(`/summoner/${region}/${summoner}`)
}, },
resetLocalStorage() { ...mapActions('summoner', ['summonerRequest'])
console.log('CLEAR LOCALSTORAGE')
localStorage.clear()
}
} }
} }
</script> </script>