mm_datas 5.3.0 → 5.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const MemoryStore = require('./memory_store.js');
6
+
7
+ /**
8
+ * JSON 文件存储:每张表一个 .json 文件
9
+ */
10
+ class JsonFileStore extends MemoryStore {
11
+ /**
12
+ * 构造函数
13
+ * @param {string} dir 数据目录
14
+ * @param {object} [options] 选项(persist/auto_save/flush_interval)
15
+ */
16
+ constructor(dir, options) {
17
+ super();
18
+ this.dir = dir;
19
+ this.backend = 'json';
20
+ this.persist = !(options && options.persist === false);
21
+ this.auto_save = !!(options && options.auto_save);
22
+ this.flush_interval = Math.max(0, Number(options && options.flush_interval) || 0);
23
+ }
24
+
25
+ /**
26
+ * 全量保存到目录
27
+ * @param {string} [dir] 数据目录,传入时更新实例目录
28
+ * @returns {object} 保存结果
29
+ */
30
+ save(dir) {
31
+ if (dir) this.dir = dir;
32
+ fs.mkdirSync(this.dir, { recursive: true });
33
+ let names = this.tableNames();
34
+ for (let i = 0; i < names.length; i++) {
35
+ let file = path.join(this.dir, names[i] + '.json');
36
+ fs.writeFileSync(file, JSON.stringify(this.getRows(names[i]), null, 2), 'utf8');
37
+ }
38
+ fs.writeFileSync(path.join(this.dir, '_tables.json'), JSON.stringify(names, null, 2), 'utf8');
39
+ this.dirty = false;
40
+ return { ok: true, backend: 'json', dir: this.dir, tables: names.length };
41
+ }
42
+
43
+ /**
44
+ * 从目录恢复
45
+ * @param {Array} [modelNames] 模型名列表,缺省读 _tables.json
46
+ * @param {string} [dir] 数据目录,传入时更新实例目录
47
+ * @returns {object} 恢复结果
48
+ */
49
+ load(modelNames, dir) {
50
+ if (dir) this.dir = dir;
51
+ if (!fs.existsSync(this.dir)) return { ok: false, reason: '目录不存在' };
52
+ let meta = path.join(this.dir, '_tables.json');
53
+ let names = modelNames;
54
+ if (!names && fs.existsSync(meta)) names = JSON.parse(fs.readFileSync(meta, 'utf8'));
55
+ if (!names) return { ok: false, reason: '缺少 _tables.json' };
56
+ for (let i = 0; i < names.length; i++) {
57
+ let file = path.join(this.dir, names[i] + '.json');
58
+ if (fs.existsSync(file)) {
59
+ this.setTable(names[i], JSON.parse(fs.readFileSync(file, 'utf8')));
60
+ }
61
+ }
62
+ return { ok: true, backend: 'json', dir: this.dir, tables: names.length, table_names: names };
63
+ }
64
+ }
65
+
66
+ module.exports = JsonFileStore;