Store users in the DB.

Properly reading from it is still not hooked up, at the moment.
This commit is contained in:
Sage Vaillancourt 2024-11-09 18:00:51 -05:00
parent 71df29b27b
commit 161780c45f
1 changed files with 15 additions and 6 deletions

View File

@ -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))
}