From 161780c45f2033229f44d4d268c87db6424610ec Mon Sep 17 00:00:00 2001 From: Sage Vaillancourt Date: Sat, 9 Nov 2024 18:00:51 -0500 Subject: [PATCH] Store users in the DB. Properly reading from it is still not hooked up, at the moment. --- src/games/hvacoins/utils.js | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/games/hvacoins/utils.js b/src/games/hvacoins/utils.js index adc608e..1dfdfe1 100644 --- a/src/games/hvacoins/utils.js +++ b/src/games/hvacoins/utils.js @@ -1,10 +1,11 @@ const { Pool } = require('pg') const fs = require('fs') +const config = require('../../config') const achievements = require('./achievements') const buyableItems = require('./buyableItems') const { quackStore, getChaos } = require('./quackstore') -const dbPool = new Pool() +const dbPool = new Pool(config.postgres) let jokes let slackUsers @@ -62,26 +63,26 @@ const parseOr = (parseable, fallback) => { } let lastBackupTs = 0 -const makeBackup = (force) => { +const makeBackup = force => { const currentTs = Date.now() if (lastBackupTs > (currentTs - 60000) && !force) { return } lastBackupTs = currentTs - const fileName = saveDir + 'backups/' + saveFile + new Date().toLocaleString().replace(/[^a-z0-9]/gi, '_') + const cleanNowString = new Date().toLocaleString().replace(/[^a-z0-9]/gi, '_') + const fileName = `${saveDir}backups/${cleanNowString}-${saveFile}` console.log(`Making backup file: ${fileName}`) fs.writeFileSync(fileName, JSON.stringify(game)) } const saveUser = async (userId, user, after) => { - return const name = user.name || userId if (after) { console.log(`SAVING ${name} after ${after}`) } else { console.log(`SAVING ${name}`, user) } - await dbPool.query(` + return await dbPool.query(` INSERT INTO hvacker_user (slack_id, name, data) VALUES ($1, $2, $3) ON CONFLICT (slack_id) DO UPDATE @@ -90,10 +91,19 @@ const saveUser = async (userId, user, after) => { .catch(console.error) } +const saveAllUsers = () => Promise.all( + Object.entries(game.users).map(async ([userId, user]) => + await saveUser(userId, user) + ) +).then(() => { + console.log('All users updated in the DB') +}) + let saves = 0 const saveGame = (after, force = true, skipLog = false) => { if (saves % 20 === 0) { makeBackup() + saveAllUsers().catch(console.error) } saves += 1 if (force || saves % 10 === 0) { @@ -104,7 +114,6 @@ const saveGame = (after, force = true, skipLog = false) => { console.log('SAVING GAME') } } - // Object.entries(game.users).forEach(([userId, user]) => saveUser(userId, user)) fs.writeFileSync(saveDir + saveFile, JSON.stringify(game, null, 2)) }