feat(persist): salva stato su .segnapunti/state.json ad ogni azione
All'avvio il server carica lo stato dal file se esiste; ad ogni azione lo riscrive. Il riavvio del server riprende dall'ultimo punto salvato.
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs'
|
||||
import { join, dirname } from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import { createInitialState } from './gameState.js'
|
||||
|
||||
const STATE_PATH = join(dirname(fileURLToPath(import.meta.url)), '..', '.segnapunti', 'state.json')
|
||||
|
||||
export function loadState() {
|
||||
try {
|
||||
if (existsSync(STATE_PATH)) {
|
||||
return JSON.parse(readFileSync(STATE_PATH, 'utf8'))
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[Persist] Stato non leggibile, si riparte da zero:', err.message)
|
||||
}
|
||||
return createInitialState()
|
||||
}
|
||||
|
||||
export function saveState(state) {
|
||||
try {
|
||||
mkdirSync(dirname(STATE_PATH), { recursive: true })
|
||||
writeFileSync(STATE_PATH, JSON.stringify(state), 'utf8')
|
||||
} catch (err) {
|
||||
console.error('[Persist] Salvataggio fallito:', err.message)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user