From 9150fd813c4a2db1a61a10c1b3a17b1d4ce380e2 Mon Sep 17 00:00:00 2001 From: Anatoly Date: Thu, 13 Jan 2022 00:56:18 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20=D0=98=D0=B7=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D1=87=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=84=D1=83=D0=BD=D0=BA=D1=86?= =?UTF-8?q?=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/index.js | 53 ++++++++++++++++++++++++------------------------ 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/backend/index.js b/backend/index.js index d314a8a..9e34b4a 100644 --- a/backend/index.js +++ b/backend/index.js @@ -51,21 +51,23 @@ cardsCollection.aggregate([ ]).toArray().then((memeCount) => { cardsCollection.countDocuments().then((totalCount) => { let quota, quotaTimes - let activeUsers = 0 quota = totalCount/memeCount.length // Квота мемов на человека console.log(totalCount + " мемов всего. Квота: " + quota) - // Подсчет количества активных пользователей - memeCount.forEach((person) => { - if (person.count > quota/10) - activeUsers++ - }) + function activeUsers() { + let activeUsers = 0 + memeCount.forEach((person) => { + if (person.count > quota/10) + activeUsers++ + }) + return activeUsers + } memeCount.forEach((person) => { // Во сколько раз превышена квота: // (колич. астивных человек в конфе * колич. мемов данного человека / мемов всего) - quotaTimes = activeUsers*person.count/totalCount + quotaTimes = activeUsers()*person.count/totalCount if (quotaTimes > 1) { dropProb[person._id] = 1 - (1/quotaTimes) } else { @@ -96,25 +98,24 @@ app.post('/api/auth', async (req, res) => { }) app.get('/api/card', async (req, res) => { + async function drawCard() { + let card + // Тянем карты и отбрасываем их в соответствии с их вероятностью отбрасывания + do { + card = await cardsCollection.aggregate([ + { + $sample: { size: 1 } + }, { + $unset: [ 'name', 'link', 'date' ] + } + ]).toArray() + card = card[0] + } while (Math.random() < dropProb[card.name]) + return card + } + if (req.session.loggedIn) { - try { - let card - // Тянем карты и отбрасываем их в соответствии с их вероятностью отбрасывания - do { - card = await cardsCollection.aggregate([ - { - $sample: { size: 1 } - }, { - $unset: [ 'name', 'link', 'date' ] - } - ]).toArray() - card = card[0] - } while (Math.random() < dropProb[card.name]) - res.status(200).send(card) - } catch (e) { - console.log("Error: " + e) - res.status(500).send() - } + res.status(200).send(await drawCard()) } else { res.status(403).send() } @@ -215,4 +216,4 @@ app.get('/api/options', async (req, res) => { } }) -app.listen(process.env.PORT, () => console.log('Server started on ' + process.env.PORT)); \ No newline at end of file +app.listen(process.env.PORT, () => console.log('Server started on ' + process.env.PORT));