UNPKG

1.94 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const fs_1 = require("fs");
4const mkdirp_1 = require("mkdirp");
5const path_1 = require("path");
6class Store {
7 constructor(path, defaults = {}, __class = null) {
8 this.path = path;
9 this.defaults = defaults;
10 if (__class !== Store.__classIdentifier)
11 throw new TypeError("'Store' is not a constructor. Use static method 'Store.from()' instead.");
12 try {
13 this.__internalValue = { ...defaults, ...require(path) };
14 }
15 catch (e) {
16 this.__internalValue = { ...defaults };
17 }
18 fs_1.watchFile(path, { persistent: false }, () => {
19 this.__internalValue = { ...defaults, ...require(path) };
20 });
21 }
22 static from(path, defaults) {
23 if (path_1.extname(path.toString()).toLowerCase() !== ".json")
24 throw new TypeError(`'${path}' is not a JSON file.`);
25 mkdirp_1.sync(path_1.resolve(path.toString(), "../"));
26 if (!fs_1.existsSync(path))
27 fs_1.writeFileSync(path, "{}");
28 return new this(path.toString(), defaults, Store.__classIdentifier);
29 }
30 clear() {
31 this.__internalValue = this.defaults;
32 fs_1.writeFileSync(this.path, JSON.stringify(this.__internalValue), "utf8");
33 return this;
34 }
35 get age() {
36 try {
37 const stat = fs_1.statSync(this.path);
38 return Math.floor(Date.now() - stat.mtimeMs);
39 }
40 catch (e) {
41 return Date.now();
42 }
43 }
44 get value() {
45 return this.__internalValue;
46 }
47 set value(newValue) {
48 this.__internalValue = { ...this.defaults, ...this.__internalValue, ...newValue };
49 fs_1.writeFileSync(this.path, JSON.stringify(this.__internalValue), "utf8");
50 }
51}
52exports.default = Store;
53Store.__classIdentifier = Symbol("Store");
54//# sourceMappingURL=index.js.map
\No newline at end of file