Skip to content

Commit

Permalink
add get statistic route
Browse files Browse the repository at this point in the history
  • Loading branch information
Lantos György committed May 20, 2020
1 parent 2ee5813 commit b812632
Show file tree
Hide file tree
Showing 10 changed files with 79 additions and 18 deletions.
9 changes: 5 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ const {
const app = require('./src/api/app');

const scrape = async () => {
await openBrowser(true);
await openBrowser(false);
try {
const currentlyListedGames = await getCurrentlyListedGames();
fs.writeFileSync('./newLeagues1.json', JSON.stringify(currentlyListedGames));
fs.writeFileSync('./newLeagues34.json', JSON.stringify(currentlyListedGames));
const newRounds = await updateGamesAndLeaguesInDB(currentlyListedGames);
const newTeamStats = await getTeamStats(newRounds);
fs.writeFileSync('./newStats2.json', JSON.stringify(newTeamStats));
fs.writeFileSync('./newStats34.json', JSON.stringify(newTeamStats));
await updateStatsInDB(newTeamStats);
} catch (e) {
console.log(e);
Expand All @@ -30,9 +30,10 @@ const scrape = async () => {
await closeBrowser();
};

// scrape();
//scrape();

const port = process.env.port || 5050;
app.listen(port, () => {
console.log(`App is listening at port ${port}`)
});

5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"express": "^4.17.1",
"helmet": "^3.22.0",
"knex": "^0.21.0",
"moment": "^2.25.3",
"morgan": "^1.10.0",
"pg": "^8.0.3",
"puppeteer": "^2.1.1"
Expand Down
1 change: 1 addition & 0 deletions src/api/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ app.get('/', (req, res) => {
});

app.use('/api/v1/games', Routes.games);
app.use('/api/v1/stat', Routes.stats);

configErrorHandler(app);

Expand Down
4 changes: 2 additions & 2 deletions src/api/config/middlewares.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ const notFound = (req, res, next) => {
next(error);
};

const errorHandler = (error, req, res) => {
const errorHandler = (error, req, res, next) => {
const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
res.status(statusCode);
res.json({
status: statusCode,
message: error.message,
message: process.env.NODE_ENV === 'production' ? '🥞' : error.message,
stack: process.env.NODE_ENV === 'production' ? '🥞' : error.stack,
});
};
Expand Down
3 changes: 1 addition & 2 deletions src/api/modules/games/gamesController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ const { getFilteredGamesFromDB } = require('../../../dbService/utils/dbOperation

const getFilteredGames = async (req,res) => {
try {
// cerate a base query body
const games = await getFilteredGamesFromDB();
res.status(200).json({ games });
res.status(200).json({ games, length: games.length });
} catch (e) {
res.status(400).json({ message: e.message });
}
Expand Down
4 changes: 3 additions & 1 deletion src/api/modules/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const games = require('./games/gamesRoutes');
const stats = require('./stats/statRoutes');

module.exports = {
games
games,
stats,
};
8 changes: 8 additions & 0 deletions src/api/modules/stats/statRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const { Router } = require('express');
const { getStatForTeam } = require('./statsController');

const routes = Router();

routes.get('/team/:teamID/:state', getStatForTeam);

module.exports = routes;
19 changes: 19 additions & 0 deletions src/api/modules/stats/statsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const { getHomeTeamStatFromDB, getAwayTeamStatFromDB } =require('../../../dbService/utils/dbOperations');

const getStatForTeam = async (req, res) => {
// TODO add validation
const teamID = req.params.teamID;
const state = req.params.state;
const statQuery = state === 'home' ? getHomeTeamStatFromDB : getAwayTeamStatFromDB;

try {
const stats = await statQuery(teamID);
res.status(200).json({ teamID, state, stats });
} catch(e) {
res.status(400).json({ message: e.message });
}
};

module.exports = {
getStatForTeam,
};
43 changes: 34 additions & 9 deletions src/dbService/utils/dbOperations.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const db = require('../db');
const tableNames = require('../constants/tableNames');
const moment = require('moment');

// Inserts
const createUpsertOrDoNothing = dataBase => tableName => conflictingFields => async dataToBeInserted =>
Expand Down Expand Up @@ -27,13 +28,13 @@ const insertIntoLeagues = createInsertIntoLeagues('name');
const insertIntoTeams = createInsertIntoTeams('name');

// Queries
const createQuery = dataBase => tableName => (...fields) => async () =>
const createBaseQuery = dataBase => tableName => (...fields) => async () =>
dataBase.from(tableName).select(fields);

const createIdQueryForName = dataBase => tableName => async name =>
dataBase.from(tableName).where('name', name).select('id').first();

const query = createQuery(db);
const query = createBaseQuery(db);
const idQuery = createIdQueryForName(db);

const createWeeklyGameHashQuery = query(tableNames.weekly_game_hash);
Expand All @@ -45,14 +46,36 @@ const getTeamIdWhereNameFromDB = idQuery(tableNames.team);
const getWeeklyGameHashFromDB = createWeeklyGameHashQuery('hash');
const getGameHashFromDB = createGameHashQuery('hash');

// TODO stat and a game queries, always pick the latest one as, there will be the data always be inserted
const getFilteredGamesFromDB = async () => {
const yesterday = moment().subtract(1, 'day').toISOString();
return db(`${tableNames.game} AS g`)
.join(`${tableNames.league} as l`, 'g.league_id', 'l.id' )
.join(`${tableNames.team} as t1`, 'g.home_team_id', 't1.id')
.join(`${tableNames.team} as t2`, 'g.away_team_id', 't2.id')
// .leftJoin(`${tableNames.weekly_home_stat} as hst`, 'g.home_team_id', 'hst.team_id')
// .leftJoin(`${tableNames.weekly_home_stat} as ast`, 'g.away_team_id', 'ast.team_id')
.select(
'l.name AS league',
't1.name AS home_team',
'g.home_team_id AS home_team_id',
'g.away_team_id AS away_team_id',
't2.name AS away_team',
'g.game_date AS date')
.where('g.game_date', '>', yesterday)
.andWhere('l.name', 'Turkey - Super Lig');
};

const createBaseStatQuery = dataBase => tableName => async id =>
dataBase.from(tableName)
.where('team_id', id)
.select('*')
.orderBy('id', 'desc')
.limit(1);

const createStatQuery = createBaseStatQuery(db);

const getFilteredGamesFromDB = async () => db(`${tableNames.game} AS g`)
.join(`${tableNames.league} as l`, 'g.league_id', 'l.id' )
.join(`${tableNames.team} as t1`, 'g.home_team_id', 't1.id')
.join(`${tableNames.team} as t2`, 'g.away_team_id', 't2.id')
.select('l.name', 't1.name', 't2.name')
.where('l.name', 'Bundesliga');
const getHomeTeamStatFromDB = createStatQuery(tableNames.weekly_home_stat);
const getAwayTeamStatFromDB = createStatQuery(tableNames.weekly_away_stat);

module.exports = {
insertIntoLeagues,
Expand All @@ -66,4 +89,6 @@ module.exports = {
getLeagueIdWhereNameFromDB,
getTeamIdWhereNameFromDB,
getFilteredGamesFromDB,
getHomeTeamStatFromDB,
getAwayTeamStatFromDB,
};

0 comments on commit b812632

Please sign in to comment.