feat: add atomic JSON file state persistence for production runtime
This commit is contained in:
37
src/lib/state-store.js
Normal file
37
src/lib/state-store.js
Normal file
@@ -0,0 +1,37 @@
|
||||
"use strict";
|
||||
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
|
||||
class JsonFileStateStore {
|
||||
constructor(filePath) {
|
||||
this.filePath = filePath;
|
||||
}
|
||||
|
||||
async load() {
|
||||
try {
|
||||
const raw = await fs.readFile(this.filePath, "utf8");
|
||||
return JSON.parse(raw);
|
||||
} catch (error) {
|
||||
if (error && error.code === "ENOENT") {
|
||||
return null;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async save(state) {
|
||||
const dir = path.dirname(this.filePath);
|
||||
await fs.mkdir(dir, { recursive: true });
|
||||
|
||||
const tempPath = `${this.filePath}.tmp`;
|
||||
const payload = JSON.stringify(state, null, 2);
|
||||
|
||||
await fs.writeFile(tempPath, payload, "utf8");
|
||||
await fs.rename(tempPath, this.filePath);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
JsonFileStateStore,
|
||||
};
|
||||
Reference in New Issue
Block a user