Created
November 28, 2018 23:16
-
-
Save vs0uz4/e1775fde9146368c0b0d07f47c3c6ecf to your computer and use it in GitHub Desktop.
Módulo 'ranking' verifica a existência dos rankings em cache, caso não existam faz a query e salva no cache (redis)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
const route = express.Router() | |
const encRedisClient = require('./cache/setup') | |
const init = connection => { | |
let classification = null | |
route.get('/', async (req, res) => { | |
if (!classification) { | |
const groupsRanking = await encRedisClient.getAsync('groupsRanking', async (err, reply) => { | |
if (err) { | |
console.log(err.message) | |
} else { | |
if (reply.length > 0) { | |
return reply | |
} else { | |
const [groups] = await connection.execute('SELECT groups.id, groups.name, SUM(guessings.score) as score FROM groups LEFT JOIN guessings ON guessings.group_id = groups.id GROUP BY groups.id ORDER BY score DESC') | |
await encRedisClient.setexAsync('groupsRanking', 84600, groups, (err) => { | |
if (err) { | |
console.log(err.message) | |
} | |
}) | |
return groups | |
} | |
} | |
}) | |
const usersRanking = await encRedisClient.getAsync('usersRanking', async (err, reply) => { | |
if (err) { | |
console.log(err.message) | |
} else { | |
if (reply.length > 0) { | |
return reply | |
} else { | |
const [users] = await connection.execute('SELECT users.id, users.name, SUM(guessings.score) as score FROM users LEFT JOIN guessings on guessings.user_id = users.id GROUP BY users.id ORDER BY score DESC') | |
await encRedisClient.setexAsync('usersRanking', 84600, users, (err) => { | |
if (err) { | |
console.log(err.message) | |
} | |
}) | |
return users | |
} | |
} | |
}) | |
classification = { | |
groupsRanking, | |
usersRanking | |
} | |
console.log(classification) | |
} | |
res.render('ranking', classification) | |
}) | |
return route | |
} | |
module.exports = init |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment