UNPKG

@towercg2/server

Version:

The server runtime for the TowerCG2 video graphics system.

35 lines (34 loc) 1.62 kB
"use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const fsx = __importStar(require("fs-extra")); const redux_1 = require("redux"); function buildStore(baseLogger, reducer, initialState, jsonReviver, jsonReplacer, filename) { const logger = baseLogger.child({ component: "Store" }); let state = initialState; if (fsx.pathExistsSync(filename)) { logger.debug("Existing state file; rehydrating for store."); const text = fsx.readFileSync(filename, { encoding: "UTF8" }); state = JSON.parse(text, jsonReviver || undefined); } const store = redux_1.createStore(reducer, state); store.subscribe(() => { // TODO: this is potentially slow. Eventually it might make sense to // turn this into an asynchronous save, but writing it properly // for linearizable saves is tricky. This at least guarantees // that writes finish before the next does and won't cause a // write storm from heavy, un-debounced updates. logger.trace("Writing to state."); const currentState = store.getState(); const text = JSON.stringify(currentState, jsonReplacer || undefined); fsx.writeFileSync(filename, text, { encoding: "UTF8" }); }); return store; } exports.buildStore = buildStore;