tsbase
Version:
Base class libraries for TypeScript
58 lines • 1.96 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FSPersister = void 0;
/**
* Persists data using the node fs / path api
*/
class FSPersister {
get dir() {
return this.pathResolver.resolve(this.localFilesDirectory);
}
get file() {
return this.pathResolver.resolve(this.localFilesDirectory, this.filePath);
}
constructor(localFilesDirectory, filePath, key, pathResolver, fileSystemAdapter) {
this.localFilesDirectory = localFilesDirectory;
this.filePath = filePath;
this.key = key;
this.pathResolver = pathResolver;
this.fileSystemAdapter = fileSystemAdapter;
this.ensureLocalFilesDirExists();
this.ensureFileExists();
}
Retrieve() {
const json = this.retrieveDataFileJson();
return json[this.key] ? json[this.key] : [];
}
Persist(items) {
const json = this.retrieveDataFileJson();
json[this.key] = items;
this.fileSystemAdapter.writeFileSync(this.file, JSON.stringify(json));
}
Purge() {
this.Persist([]);
}
ensureLocalFilesDirExists() {
if (!this.fileSystemAdapter.existsSync(this.dir)) {
this.fileSystemAdapter.mkdirSync(this.dir);
}
}
ensureFileExists() {
try {
this.fileSystemAdapter.accessSync(this.file, this.fileSystemAdapter.constants.W_OK);
}
catch (error) {
this.writeBlankJsonToFile();
}
}
writeBlankJsonToFile() {
const blankJson = {};
this.fileSystemAdapter.writeFileSync(this.file, JSON.stringify(blankJson));
}
retrieveDataFileJson() {
const fileContents = this.fileSystemAdapter.readFileSync(this.pathResolver.resolve(this.localFilesDirectory, this.filePath), 'utf8');
return JSON.parse(fileContents.toString());
}
}
exports.FSPersister = FSPersister;
//# sourceMappingURL=FSPersister.js.map