signalk-server
Version:
An implementation of a [Signal K](http://signalk.org) server for boats.
57 lines (56 loc) • 2.15 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Store = exports.SERVERSTATEDIRNAME = void 0;
const fs_1 = require("fs");
const promises_1 = require("fs/promises");
const path_1 = __importDefault(require("path"));
exports.SERVERSTATEDIRNAME = 'serverState';
class Store {
filePath = '';
fileName = '';
initPromise = null;
constructor(server, storePath, fileName = 'settings.json') {
this.filePath = path_1.default.join(server.config.configPath, exports.SERVERSTATEDIRNAME, storePath);
this.fileName = fileName;
this.initPromise = this.init().catch((error) => {
console.log(`Could not initialise ${path_1.default.join(this.filePath, this.fileName)}`);
console.log(error);
});
}
// Wait for initialization to complete before performing operations
async waitForInit() {
if (this.initPromise) {
await this.initPromise;
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async read() {
await this.waitForInit();
const data = await (0, promises_1.readFile)(path_1.default.join(this.filePath, this.fileName), 'utf8');
return JSON.parse(data);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async write(data) {
await this.waitForInit();
return (0, promises_1.writeFile)(path_1.default.join(this.filePath, this.fileName), JSON.stringify(data));
}
async init() {
try {
/* tslint:disable:no-bitwise */
await (0, promises_1.access)(this.filePath, fs_1.constants.R_OK | fs_1.constants.W_OK);
/* tslint:enable:no-bitwise */
}
catch (_error) {
try {
await (0, promises_1.mkdir)(this.filePath, { recursive: true });
}
catch (_error) {
console.log(`Error: Unable to create ${this.filePath}`);
}
}
}
}
exports.Store = Store;