puzzle/src/server/GameLog.ts

52 lines
1 KiB
TypeScript
Raw Normal View History

2020-12-22 22:35:09 +01:00
import fs from 'fs'
import { logger } from './../common/Util'
import { DATA_DIR } from './../server/Dirs'
const log = logger('GameLog.js')
2020-12-22 22:35:09 +01:00
2021-05-17 00:27:47 +02:00
const filename = (gameId: string) => `${DATA_DIR}/log_${gameId}.log`
2020-12-22 22:54:31 +01:00
2021-05-17 00:27:47 +02:00
const create = (gameId: string) => {
2020-12-22 22:54:31 +01:00
const file = filename(gameId)
if (!fs.existsSync(file)) {
fs.appendFileSync(file, '')
}
}
2021-05-17 00:27:47 +02:00
const exists = (gameId: string) => {
2020-12-22 22:54:31 +01:00
const file = filename(gameId)
return fs.existsSync(file)
}
2021-05-17 00:27:47 +02:00
const _log = (gameId: string, ...args: Array<any>) => {
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
}
2021-05-17 00:27:47 +02:00
const get = (gameId: string) => {
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")
2021-05-17 00:27:47 +02:00
return lines.filter((line: string) => !!line).map((line: string) => {
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,
}