LeagueStats/server/server.js

145 lines
4.4 KiB
JavaScript
Raw Normal View History

2019-03-30 22:55:48 +00:00
require('dotenv').config()
const express = require('express')
const request = require('request');
const bodyParser = require('body-parser');
const rp = require('request-promise');
const Promise = require("bluebird");
2019-05-17 21:09:48 +00:00
const responseTime = require('response-time')
2019-08-19 11:18:06 +00:00
const cors = require('cors');
2019-03-30 22:55:48 +00:00
const app = express()
/* Global Variables */
2019-04-07 17:44:01 +00:00
const data = {
key: process.env.API_KEY,
region: 'euw1',
summonerID: '',
accountID: '',
username: '',
JSONMatches: [],
finalJSON: []
}
2019-03-30 22:55:48 +00:00
/* Set Port */
app.set('port', (process.env.PORT || 5000))
2019-08-19 11:18:06 +00:00
/* Setup Cors */
app.use(cors({
origin: [
'http://localhost:8080',
'https://leaguestats-gg.netlify.com',
'https://leaguestats.valentinkaelin.ch/'
]
}));
/* Setup Production */
if (process.env.NODE_ENV !== 'development') {
2019-04-07 17:44:01 +00:00
const path = require('path');
const history = require('connect-history-api-fallback');
const staticFileMiddleware = express.static(path.join(__dirname + '/dist'));
app.use(staticFileMiddleware);
app.use(history({
disableDotRule: true,
verbose: true
}));
app.use(staticFileMiddleware);
2019-04-05 20:41:32 +00:00
2019-04-07 17:44:01 +00:00
app.get('/', function (req, res) {
res.render(path.join(__dirname + '/dist/index.html'));
});
}
2019-03-30 22:55:48 +00:00
/* To retrieve data of post request */
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
2019-08-19 11:18:06 +00:00
extended: true
2019-03-30 22:55:48 +00:00
}));
2019-05-17 21:09:48 +00:00
// Create a middleware that adds a X-Response-Time header to responses
app.use(responseTime());
2019-03-30 22:55:48 +00:00
/* Launch app */
app.listen(app.get('port'), () => console.log(`RiotAPI app listening on port ${app.get('port')}!`))
// Send data of a summoner
app.post('/api', function (req, res) {
console.log('API Request');
console.log(req.body.summoner);
2019-04-08 20:06:22 +00:00
console.log(req.body.region);
2019-03-30 22:55:48 +00:00
//console.log(req.body.playerName);
console.time('all')
2019-04-08 20:06:22 +00:00
data.region = req.body.region;
2019-04-07 17:44:01 +00:00
data.username = req.body.summoner;
data.finalJSON = [];
2019-03-30 22:55:48 +00:00
getAccountInfos(res);
});
// Get account infos of an username
const getAccountInfos = function (res) {
2019-04-07 17:44:01 +00:00
request(`https://${data.region}.api.riotgames.com/lol/summoner/v4/summoners/by-name/${encodeURIComponent(data.username)}?api_key=${data.key}`, function (error, response, body) {
2019-03-30 22:55:48 +00:00
if (!error && response.statusCode == 200) {
let JSONBody = JSON.parse(body);
2019-04-07 17:44:01 +00:00
data.summonerID = JSONBody.id;
data.accountID = JSONBody.accountId;
data.finalJSON.push(JSONBody)
2019-03-30 22:55:48 +00:00
getRanked(res);
}
else {
console.log(response.statusCode);
console.log('username not found');
res.send(null);
}
});
}
// Get data of rankeds stats
const getRanked = function (res) {
2019-06-21 17:01:27 +00:00
request(`https://${data.region}.api.riotgames.com/lol/league/v4/entries/by-summoner/${data.summonerID}?api_key=${data.key}`, function (error, response, body) {
2019-03-30 22:55:48 +00:00
if (!error && response.statusCode == 200) {
let JSONBody = JSON.parse(body).filter(e => e.queueType !== 'RANKED_TFT');
2019-03-30 22:55:48 +00:00
if (JSONBody.length > 0) {
2019-04-07 17:44:01 +00:00
data.finalJSON.push(...JSONBody);
if (JSONBody.length === 1) data.finalJSON.push(null);
2019-03-30 22:55:48 +00:00
} else {
console.log('empty rank stats')
2019-04-07 17:44:01 +00:00
data.finalJSON.push(null, null);
2019-03-30 22:55:48 +00:00
}
getMatches(res);
}
})
}
2019-08-19 22:08:13 +00:00
// Get 100 matches basic infos and 10 matches details of an accountID
2019-03-30 22:55:48 +00:00
const getMatches = function (res) {
console.time('getMatches');
2019-08-19 22:08:13 +00:00
request(`https://${data.region}.api.riotgames.com/lol/match/v4/matchlists/by-account/${data.accountID}?endIndex=100&api_key=${data.key}`, function (error, response, body) {
2019-03-30 22:55:48 +00:00
if (!error && response.statusCode == 200) {
2019-08-19 22:08:13 +00:00
const allMatches = JSON.parse(body)
data.JSONMatches = allMatches.matches.slice(0, 10)
const matchsId = data.JSONMatches.map(x => x.gameId)
2019-03-30 22:55:48 +00:00
Promise.map(matchsId, function (id) {
return getMatch('match/v4/matches/' + id);
}).then(() => {
console.timeEnd('getMatches');
console.log('Finished - Data sent to front');
2019-04-07 17:44:01 +00:00
data.finalJSON.push(data.JSONMatches)
2019-08-19 22:08:13 +00:00
data.finalJSON.push(allMatches)
2019-04-07 17:44:01 +00:00
res.send(data.finalJSON);
2019-03-30 22:55:48 +00:00
console.timeEnd('all')
}).catch(err => {
console.log('Error Promise');
console.log(err);
});
}
});
}
// Get data of one match
const getMatch = async function (urlApi) {
//console.log(urlApi);
2019-04-07 17:44:01 +00:00
return rp({ url: `https://${data.region}.api.riotgames.com/lol/${urlApi}?api_key=${data.key}`, json: true }).then(function (obj) {
2019-08-19 22:08:13 +00:00
data.JSONMatches = data.JSONMatches.map((match) => match.gameId === obj.gameId ? obj : match);
2019-03-30 22:55:48 +00:00
});
}