Use ES6 for variables and hide API_KEY

This commit is contained in:
Valentin Kaelin 2019-03-24 20:25:45 +01:00
parent 79856538bf
commit d38d82c128
5 changed files with 93 additions and 90 deletions

3
.gitignore vendored
View file

@ -1,2 +1,3 @@
/node_modules /node_modules
/Patch9.5 /Patch9.5
.env

5
package-lock.json generated
View file

@ -161,6 +161,11 @@
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
"integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
}, },
"dotenv": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-7.0.0.tgz",
"integrity": "sha512-M3NhsLbV1i6HuGzBUH8vXrtxOk+tWmzWKDMbAVSUp3Zsjm7ywFeuwrUXhmhQyRK1q5B5GGy7hcXPbj3bnfZg2g=="
},
"ecc-jsbn": { "ecc-jsbn": {
"version": "0.1.2", "version": "0.1.2",
"resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz",

View file

@ -11,6 +11,7 @@
"dependencies": { "dependencies": {
"bluebird": "^3.5.3", "bluebird": "^3.5.3",
"body-parser": "^1.18.3", "body-parser": "^1.18.3",
"dotenv": "^7.0.0",
"express": "^4.16.4", "express": "^4.16.4",
"request": "^2.88.0", "request": "^2.88.0",
"request-promise": "^4.2.2" "request-promise": "^4.2.2"

View file

@ -1,12 +1,12 @@
var req = new XMLHttpRequest(); const req = new XMLHttpRequest();
var url = '/api'; const url = '/api';
var nameChosen = ''; const localInfos = {};
var localInfos = {}; let nameChosen = '';
var itemsJSON; let itemsJSON;
// Get username from param // Get username from param
let fullUrl = new URL(window.location.href); const fullUrl = new URL(window.location.href);
let searchParams = new URLSearchParams(fullUrl.search); const searchParams = new URLSearchParams(fullUrl.search);
nameChosen = searchParams.get('username'); nameChosen = searchParams.get('username');
/** /**
@ -46,7 +46,7 @@ async function main() {
}); });
/* Refresh button */ /* Refresh button */
var refreshBtn = document.querySelector('#refresh'); const refreshBtn = document.querySelector('#refresh');
refreshBtn.addEventListener('click', (e) => { refreshBtn.addEventListener('click', (e) => {
e.preventDefault(); e.preventDefault();
document.querySelector('.loader--overlay').style.display = 'block'; document.querySelector('.loader--overlay').style.display = 'block';
@ -62,7 +62,7 @@ main();
function onLoad() { function onLoad() {
document.querySelector('.loader--overlay').style.display = 'none'; document.querySelector('.loader--overlay').style.display = 'none';
var response = this.responseText; const response = this.responseText;
// If username isn't found // If username isn't found
if (!response) { if (!response) {
@ -71,7 +71,7 @@ function onLoad() {
return; return;
} }
document.querySelector('#refresh').style.display = 'block'; document.querySelector('#refresh').style.display = 'block';
var parsedEntireResponse = JSON.parse(response); const parsedEntireResponse = JSON.parse(response);
parsedEntireResponse[1] = JSON.parse(parsedEntireResponse[1]); parsedEntireResponse[1] = JSON.parse(parsedEntireResponse[1]);
createObject(parsedEntireResponse); createObject(parsedEntireResponse);
} }
@ -88,23 +88,23 @@ function createObject(JSONData) {
console.log('--- ALL INFOS ---') console.log('--- ALL INFOS ---')
console.log(JSONData); console.log(JSONData);
var userStats = JSONData[0]; const userStats = JSONData[0];
var rankedStats = JSONData[1]; const rankedStats = JSONData[1];
var soloQStats = rankedStats.length !== 0 ? (rankedStats[0].queueType == 'RANKED_SOLO_5x5' ? rankedStats[0] : rankedStats[1]) : false; const soloQStats = rankedStats.length !== 0 ? (rankedStats[0].queueType == 'RANKED_SOLO_5x5' ? rankedStats[0] : rankedStats[1]) : false;
var matches = JSONData[2].matches; const matches = JSONData[2].matches;
var matchesInfos = []; const matchesInfos = [];
// Loop on all matches // Loop on all matches
for (let i = 0; i < matches.length; i++) { for (let i = 0; i < matches.length; i++) {
var currentMatch = matches[i]; const currentMatch = matches[i];
var participantId; let participantId;
for (let i = 0; i < currentMatch.participantIdentities.length; i++) { for (let i = 0; i < currentMatch.participantIdentities.length; i++) {
if (currentMatch.participantIdentities[i].player.accountId === userStats.accountId) if (currentMatch.participantIdentities[i].player.accountId === userStats.accountId)
participantId = currentMatch.participantIdentities[i].participantId; participantId = currentMatch.participantIdentities[i].participantId;
} }
var teamId = currentMatch.participants[participantId - 1].teamId; const teamId = currentMatch.participants[participantId - 1].teamId;
var win = false; let win = false;
for (let i = 0; i < currentMatch.teams.length; i++) { for (let i = 0; i < currentMatch.teams.length; i++) {
if (currentMatch.teams[i].teamId === teamId) { if (currentMatch.teams[i].teamId === teamId) {
if (currentMatch.teams[i].win === 'Win') if (currentMatch.teams[i].win === 'Win')
@ -112,27 +112,27 @@ function createObject(JSONData) {
} }
} }
var map = maps[currentMatch.mapId]; const map = maps[currentMatch.mapId];
var mode = gameModes[currentMatch.queueId]; const mode = gameModes[currentMatch.queueId];
if (!mode) if (!mode)
mode = 'Undefinded gamemode'; mode = 'Undefinded gamemode';
var champion = currentMatch.participants[participantId - 1].championId; const champion = currentMatch.participants[participantId - 1].championId;
var role = currentMatch.participants[participantId - 1].timeline.lane; const role = currentMatch.participants[participantId - 1].timeline.lane;
var timeAgo = timeDifference(currentMatch.gameCreation); const timeAgo = timeDifference(currentMatch.gameCreation);
var time = secToTime(currentMatch.gameDuration); const time = secToTime(currentMatch.gameDuration);
var kills = currentMatch.participants[participantId - 1].stats.kills; const kills = currentMatch.participants[participantId - 1].stats.kills;
var deaths = currentMatch.participants[participantId - 1].stats.deaths; const deaths = currentMatch.participants[participantId - 1].stats.deaths;
var assists = currentMatch.participants[participantId - 1].stats.assists; const assists = currentMatch.participants[participantId - 1].stats.assists;
var level = currentMatch.participants[participantId - 1].stats.champLevel; const level = currentMatch.participants[participantId - 1].stats.champLevel;
var items = []; const items = [];
for (let i = 0; i < 6; i++) { for (let i = 0; i < 6; i++) {
var currentItem = 'item' + i; const currentItem = 'item' + i;
items.push(currentMatch.participants[participantId - 1].stats[currentItem]); items.push(currentMatch.participants[participantId - 1].stats[currentItem]);
} }
var gold = (currentMatch.participants[participantId - 1].stats.goldEarned / 1000).toFixed(1) + 'k'; const gold = (currentMatch.participants[participantId - 1].stats.goldEarned / 1000).toFixed(1) + 'k';
var minions = currentMatch.participants[participantId - 1].stats.totalMinionsKilled + currentMatch.participants[participantId - 1].stats.neutralMinionsKilled; const minions = currentMatch.participants[participantId - 1].stats.totalMinionsKilled + currentMatch.participants[participantId - 1].stats.neutralMinionsKilled;
matchesInfos.push({ matchesInfos.push({
result: win, result: win,
@ -178,7 +178,7 @@ function createObject(JSONData) {
* @param stringData : Stringify object with all datas * @param stringData : Stringify object with all datas
*/ */
function displayContent(stringData) { function displayContent(stringData) {
var data = JSON.parse(stringData); const data = JSON.parse(stringData);
document.querySelector('.player__pp').style.background = 'url(https://cdn.valentinkaelin.ch/riot/profileicon/' + data.profileIconId + '.png) center/cover'; document.querySelector('.player__pp').style.background = 'url(https://cdn.valentinkaelin.ch/riot/profileicon/' + data.profileIconId + '.png) center/cover';
document.querySelector('.player__name').innerHTML = data.name; document.querySelector('.player__name').innerHTML = data.name;
@ -187,17 +187,17 @@ function displayContent(stringData) {
document.querySelector('.player__rank-img').style.background = 'url(' + data.rankImgLink + ') center/cover'; document.querySelector('.player__rank-img').style.background = 'url(' + data.rankImgLink + ') center/cover';
document.querySelector('.player__ratio').innerHTML = data.rankedWins ? data.rankedWins + ' wins / ' + data.rankedLosses + ' losses' : "Joueur non classé"; document.querySelector('.player__ratio').innerHTML = data.rankedWins ? data.rankedWins + ' wins / ' + data.rankedLosses + ' losses' : "Joueur non classé";
var playerContainer = document.querySelector('.player'); const playerContainer = document.querySelector('.player');
var oldList = document.querySelector('.list-matches'); const oldList = document.querySelector('.list-matches');
if (oldList) if (oldList)
oldList.parentNode.removeChild(oldList); oldList.parentNode.removeChild(oldList);
var matchesList = document.createElement('ul'); const matchesList = document.createElement('ul');
matchesList.className = 'list-matches'; matchesList.className = 'list-matches';
playerContainer.appendChild(matchesList); playerContainer.appendChild(matchesList);
/* Loop on all matches */ /* Loop on all matches */
data.matches.forEach(e => { data.matches.forEach(e => {
var li = createHTMLOneMatch(e); const li = createHTMLOneMatch(e);
matchesList.appendChild(li); matchesList.appendChild(li);
}); });
} }
@ -208,35 +208,35 @@ function displayContent(stringData) {
* @param e : Infos in JSON of the match * @param e : Infos in JSON of the match
*/ */
function createHTMLOneMatch(e) { function createHTMLOneMatch(e) {
var li = document.createElement('li'); const li = document.createElement('li');
li.className = e.result ? 'match win' : 'match lose'; li.className = e.result ? 'match win' : 'match lose';
var container = document.createElement('div'); const container = document.createElement('div');
container.className = 'content-container'; container.className = 'content-container';
/* First col (champion/summoners) */ /* First col (champion/summoners) */
var first = document.createElement('div'); const first = document.createElement('div');
first.className = 'first'; first.className = 'first';
var imgChamp = document.createElement('img'); const imgChamp = document.createElement('img');
var championName = championsId[e.champ]; const championName = championsId[e.champ];
imgChamp.setAttribute('src', 'https://cdn.valentinkaelin.ch/riot/champions/' + championName + '.png'); imgChamp.setAttribute('src', 'https://cdn.valentinkaelin.ch/riot/champions/' + championName + '.png');
imgChamp.className = 'champion-icon'; imgChamp.className = 'champion-icon';
var level = document.createElement('span'); const level = document.createElement('span');
level.className = 'level'; level.className = 'level';
level.innerText = e.level; level.innerText = e.level;
var summonerSpells = document.createElement('div'); const summonerSpells = document.createElement('div');
summonerSpells.className = 'summonerSpells'; summonerSpells.className = 'summonerSpells';
var firstSpell = document.createElement('img'); const firstSpell = document.createElement('img');
firstSpell.setAttribute('src', 'https://cdn.valentinkaelin.ch/riot/spells/SummonerFlash.png'); firstSpell.setAttribute('src', 'https://cdn.valentinkaelin.ch/riot/spells/SummonerFlash.png');
firstSpell.className = 'spell-icon'; firstSpell.className = 'spell-icon';
summonerSpells.appendChild(firstSpell); summonerSpells.appendChild(firstSpell);
var secondSpell = document.createElement('img'); const secondSpell = document.createElement('img');
secondSpell.setAttribute('src', 'https://cdn.valentinkaelin.ch/riot/spells/SummonerDot.png'); secondSpell.setAttribute('src', 'https://cdn.valentinkaelin.ch/riot/spells/SummonerDot.png');
secondSpell.className = 'spell-icon'; secondSpell.className = 'spell-icon';
summonerSpells.appendChild(secondSpell); summonerSpells.appendChild(secondSpell);
var name = document.createElement('span'); const name = document.createElement('span');
name.className = 'champion-name'; name.className = 'champion-name';
name.innerText = championName; name.innerText = championName;
@ -246,12 +246,12 @@ function createHTMLOneMatch(e) {
first.appendChild(name); first.appendChild(name);
/* Second col (gamemode) */ /* Second col (gamemode) */
var second = document.createElement('div'); const second = document.createElement('div');
second.className = 'second'; second.className = 'second';
var map = document.createElement('div'); const map = document.createElement('div');
map.className = 'map'; map.className = 'map';
map.innerText = e.map; map.innerText = e.map;
var gamemode = document.createElement('div'); const gamemode = document.createElement('div');
gamemode.className = 'gamemode'; gamemode.className = 'gamemode';
gamemode.innerText = e.gamemode; gamemode.innerText = e.gamemode;
@ -259,17 +259,14 @@ function createHTMLOneMatch(e) {
second.appendChild(gamemode); second.appendChild(gamemode);
/* Third col (items) */ /* Third col (items) */
var third = document.createElement('div'); const third = document.createElement('div');
third.className = 'third'; third.className = 'third';
e.items.forEach(e => { e.items.forEach(e => {
var img = document.createElement('div'); const img = document.createElement('div');
img.className = 'item ' + e; img.className = 'item ' + e;
if(e !== 0) { if(e !== 0) {
var itemImage = itemsJSON.data[e].image; const itemImage = itemsJSON.data[e].image;
var itemSprite = itemImage.sprite; img.style.background = `url('https://cdn.valentinkaelin.ch/riot/${itemImage.sprite}') -${itemImage.x}px -${itemImage.y}px`;
var itemSpriteX = itemImage.x;
var itemSpriteY = itemImage.y;
img.style.background = `url('https://cdn.valentinkaelin.ch/riot/${itemSprite}') -${itemSpriteX}px -${itemSpriteY}px`;
} else { } else {
img.style.background = "url('https://cdn.valentinkaelin.ch/riot/items/0.png') 0% 0% / cover"; img.style.background = "url('https://cdn.valentinkaelin.ch/riot/items/0.png') 0% 0% / cover";
} }
@ -277,29 +274,29 @@ function createHTMLOneMatch(e) {
}); });
/* Fourth col (stats) */ /* Fourth col (stats) */
var fourth = document.createElement('div'); const fourth = document.createElement('div');
fourth.className = 'fourth'; fourth.className = 'fourth';
var score = document.createElement('div'); const score = document.createElement('div');
score.className = 'score'; score.className = 'score';
score.innerText = e.kills + '/' + e.deaths + '/' + e.assists; score.innerText = e.kills + '/' + e.deaths + '/' + e.assists;
var goldFarm = document.createElement('div'); const goldFarm = document.createElement('div');
goldFarm.className = 'gold-farm'; goldFarm.className = 'gold-farm';
var gold = document.createElement('div'); const gold = document.createElement('div');
gold.className = 'gold'; gold.className = 'gold';
gold.innerText = e.gold; gold.innerText = e.gold;
var farm = document.createElement('div'); const farm = document.createElement('div');
farm.className = 'farm'; farm.className = 'farm';
farm.innerText = e.minions; farm.innerText = e.minions;
goldFarm.appendChild(gold); goldFarm.appendChild(gold);
goldFarm.appendChild(farm); goldFarm.appendChild(farm);
var durationDate = document.createElement('div'); const durationDate = document.createElement('div');
durationDate.className = 'duration-date'; durationDate.className = 'duration-date';
var duration = document.createElement('div'); const duration = document.createElement('div');
duration.className = 'duration'; duration.className = 'duration';
duration.innerText = e.time; duration.innerText = e.time;
var date = document.createElement('div'); const date = document.createElement('div');
date.className = 'date'; date.className = 'date';
date.innerText = e.date; date.innerText = e.date;
durationDate.appendChild(duration); durationDate.appendChild(duration);
@ -331,4 +328,4 @@ function displayPlayerNotFound(text) {
document.querySelector('.player__rank-img').style.background = 'https://cdn.valentinkaelin.ch/riot/tier-icons/provisional.png'; document.querySelector('.player__rank-img').style.background = 'https://cdn.valentinkaelin.ch/riot/tier-icons/provisional.png';
document.querySelector('.player__ratio').innerHTML = text; document.querySelector('.player__ratio').innerHTML = text;
document.querySelector('.list-matches').innerHTML = ''; document.querySelector('.list-matches').innerHTML = '';
} }

View file

@ -1,18 +1,21 @@
require('dotenv').config()
const express = require('express') const express = require('express')
const request = require('request'); const request = require('request');
const path = require('path'); const path = require('path');
const bodyParser = require('body-parser'); const bodyParser = require('body-parser');
const rp = require('request-promise'); const rp = require('request-promise');
var Promise = require("bluebird"); const Promise = require("bluebird");
const app = express() const app = express()
app.set('port', (process.env.PORT || 5000))
const key = 'RGAPI-a9f85905-6287-4c29-bf01-8d8c56e9f75f'; /* Global Variables */
var summonerID = 'HMOiIUvzYtfgPk5X53zWTeOZo52T-HYJQhwvhkPNh0BWxZ0'; const key = process.env.API_KEY;
var accountID = 'V1xNS14bjVeP54hg03JeMxkXJB29K4TfUMvijDB85nxbD4Y'; let summonerID;
var pseudo = 'Chil'; let accountID;
var JSONMatches; let username;
let JSONMatches;
/* Set Port */
app.set('port', (process.env.PORT || 5000))
/* To retrieve data of post request */ /* To retrieve data of post request */
app.use(bodyParser.json()); // to support JSON-encoded bodies app.use(bodyParser.json()); // to support JSON-encoded bodies
@ -25,7 +28,7 @@ app.get('/', function (request, response) {
response.sendFile(path.join(__dirname, 'home.html')); response.sendFile(path.join(__dirname, 'home.html'));
}); });
/* Summoners pages */
app.get('/summoners', function (request, response) { app.get('/summoners', function (request, response) {
response.sendFile(path.join(__dirname, 'summoner.html')); response.sendFile(path.join(__dirname, 'summoner.html'));
}); });
@ -36,9 +39,7 @@ app.use('/public', express.static(__dirname + '/public'));
/* Launch app */ /* Launch app */
app.listen(app.get('port'), () => console.log(`RiotAPI test app listening on port ${app.get('port')}!`)) app.listen(app.get('port'), () => console.log(`RiotAPI test app listening on port ${app.get('port')}!`))
// Get data of one match
async function apicall(urlApi) { async function apicall(urlApi) {
//console.log(urlApi); //console.log(urlApi);
return rp({ url: 'https://euw1.api.riotgames.com/lol/match/v4/matches/' + urlApi + '?api_key=' + key, json: true }).then(function (obj) { return rp({ url: 'https://euw1.api.riotgames.com/lol/match/v4/matches/' + urlApi + '?api_key=' + key, json: true }).then(function (obj) {
@ -46,7 +47,6 @@ async function apicall(urlApi) {
}); });
} }
// Get data of rankeds // Get data of rankeds
function getRanked(callback) { function getRanked(callback) {
request('https://euw1.api.riotgames.com/lol/league/v4/positions/by-summoner/' + summonerID + '?api_key=' + key, function (error, response, body) { request('https://euw1.api.riotgames.com/lol/league/v4/positions/by-summoner/' + summonerID + '?api_key=' + key, function (error, response, body) {
@ -56,19 +56,18 @@ function getRanked(callback) {
}) })
} }
// send data of rankeds and of username // send data of rankeds and of username
app.post('/api', function (req, res) { app.post('/api', function (req, res) {
//console.log(req.body.playerName); //console.log(req.body.playerName);
console.time('all') console.time('all')
pseudo = req.body.playerName; username = req.body.playerName;
getAccountInfos(function (account) { getAccountInfos(function (account) {
if (!account) if (!account)
res.send(null) res.send(null)
getRanked(function (ranked) { getRanked(function (ranked) {
getMatches(function (matches) { getMatches(function (matches) {
var finalJSON = new Array(); let finalJSON = [];
finalJSON.push(account); finalJSON.push(account);
finalJSON.push(ranked); finalJSON.push(ranked);
finalJSON.push(matches); finalJSON.push(matches);
@ -84,9 +83,9 @@ app.post('/api', function (req, res) {
// Get account infos of an username // Get account infos of an username
function getAccountInfos(callback) { function getAccountInfos(callback) {
request('https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/' + encodeURIComponent(pseudo) + '?api_key=' + key, function (error, response, body) { request('https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/' + encodeURIComponent(username) + '?api_key=' + key, function (error, response, body) {
if (!error && response.statusCode == 200) { if (!error && response.statusCode == 200) {
var JSONBody = JSON.parse(body); let JSONBody = JSON.parse(body);
//console.log(JSONBody); //console.log(JSONBody);
summonerID = JSONBody.id; summonerID = JSONBody.id;
accountID = JSONBody.accountId; accountID = JSONBody.accountId;
@ -108,8 +107,8 @@ function getMatches(callback) {
if (!error && response.statusCode == 200) { if (!error && response.statusCode == 200) {
JSONMatches = JSON.parse(body); JSONMatches = JSON.parse(body);
var matchsId = new Array(); let matchsId = [];
for (var i = 0; i < JSONMatches.matches.length; i++) { for (let i = 0; i < JSONMatches.matches.length; i++) {
matchsId[i] = JSONMatches.matches[i].gameId; matchsId[i] = JSONMatches.matches[i].gameId;
} }
@ -128,10 +127,10 @@ function getMatches(callback) {
}); });
} }
// Add match to global JSON
function addMatchToJSON(obj) { function addMatchToJSON(obj) {
//console.log(obj.gameId); //console.log(obj.gameId);
for (var i = 0; i < JSONMatches.matches.length; i++) { for (let i = 0; i < JSONMatches.matches.length; i++) {
if (JSONMatches.matches[i].gameId == obj.gameId) { if (JSONMatches.matches[i].gameId == obj.gameId) {
//console.log('yes'); //console.log('yes');
JSONMatches.matches[i] = obj; JSONMatches.matches[i] = obj;