puzzle/server/GameLog.js

52 lines
1,004 B
JavaScript
Raw Normal View History

2020-12-22 22:35:09 +01:00
import fs from 'fs'
import { logger } from '../common/Util.js'
import { DATA_DIR } from '../server/Dirs.js'
const log = logger('GameLog.js')
2020-12-22 22:35:09 +01:00
2020-12-22 22:54:31 +01:00
const filename = (gameId) => `${DATA_DIR}/log_${gameId}.log`
const create = (gameId) => {
const file = filename(gameId)
if (!fs.existsSync(file)) {
fs.appendFileSync(file, '')
}
}
const exists = (gameId) => {
const file = filename(gameId)
return fs.existsSync(file)
}
const _log = (gameId, ...args) => {
2020-12-22 22:54:31 +01:00
const file = filename(gameId)
if (!fs.existsSync(file)) {
return
}
2020-12-22 22:35:09 +01:00
const str = JSON.stringify(args)
2020-12-22 22:54:31 +01:00
fs.appendFileSync(file, str + "\n")
2020-12-22 22:35:09 +01:00
}
const get = (gameId) => {
2020-12-22 22:54:31 +01:00
const file = filename(gameId)
if (!fs.existsSync(file)) {
return []
}
const lines = fs.readFileSync(file, 'utf-8').split("\n")
return lines.filter(line => !!line).map((line) => {
2020-12-22 22:35:09 +01:00
try {
return JSON.parse(line)
} catch (e) {
log.log(line)
log.log(e)
2020-12-22 22:35:09 +01:00
}
})
}
export default {
2020-12-22 22:54:31 +01:00
create,
exists,
log: _log,
2020-12-22 22:35:09 +01:00
get,
}