mm_cachebase 1.9.4 → 1.9.6

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.
Files changed (3) hide show
  1. package/index.js +137 -99
  2. package/package.json +1 -1
  3. package/test.js +29 -20
package/index.js CHANGED
@@ -14,7 +14,8 @@ class CacheBase extends Base {
14
14
  static config = {
15
15
  enabled: true,
16
16
  persist: true,
17
- file_path: './cache/base.json',
17
+ scope: 'sys',
18
+ dir: './cache',
18
19
  debug: false,
19
20
  auto_save: true,
20
21
  save_interval: 30000,
@@ -28,7 +29,9 @@ class CacheBase extends Base {
28
29
  * @param {Object} config - 配置对象
29
30
  */
30
31
  constructor(config = {}) {
32
+ // 先调用父类构造函数
31
33
  super(CacheBase.config);
34
+
32
35
  // 存储实际数据
33
36
  this._data = {};
34
37
 
@@ -54,15 +57,26 @@ class CacheBase extends Base {
54
57
  }
55
58
  }
56
59
 
60
+ /**
61
+ * 设置配置
62
+ * @param {Object} config - 配置对象
63
+ */
64
+ CacheBase.prototype.setConfig = function (config) {
65
+ // 加载外部配置文件
66
+ const external_config = this._loadExternalConfig();
67
+ // 更新配置
68
+ Object.assign(this.config, external_config, config);
69
+ }
70
+
57
71
  /**
58
72
  * 初始化服务
59
73
  * @returns {Promise<void>}
60
74
  */
61
- CacheBase.prototype.init = async function() {
75
+ CacheBase.prototype.init = async function () {
62
76
  if (this.is_inited || this.is_destroyed) {
63
77
  return;
64
78
  }
65
-
79
+
66
80
  try {
67
81
  await this._initService();
68
82
  this.is_inited = true;
@@ -73,20 +87,44 @@ CacheBase.prototype.init = async function() {
73
87
  };
74
88
 
75
89
  /**
76
- * 初始化服务
77
- * @private
78
- * @returns {Promise<void>}
79
- */
80
- CacheBase.prototype._initService = async function() {
90
+ * 加载外部配置文件
91
+ * @private
92
+ * @returns {Object} 外部配置对象
93
+ */
94
+ CacheBase.prototype._loadExternalConfig = function () {
81
95
  try {
82
- // 加载配置文件中的配置 - 使用字符串路径的原型函数
83
96
  const config_path = './config/cachebase.config.json'.fullname(__dirname);
84
97
  if (config_path.hasFile()) {
85
- // 使用mm_expand的原型函数读取JSON文件
86
98
  const config = config_path.loadJson();
87
- this.setConfig(config);
99
+ this.log('info', '外部配置文件加载成功');
100
+ return config;
88
101
  }
102
+ } catch (error) {
103
+ this.log('warn', '外部配置文件加载失败,使用默认配置:', error.message);
104
+ }
105
+ return {};
106
+ };
107
+
108
+ /**
109
+ * 设置文件路径
110
+ * @private
111
+ */
112
+ CacheBase.prototype._setFilePath = function () {
113
+ const scope = this.config.scope || 'sys';
114
+ const dir = this.config.dir || './cache';
115
+ this.file_path = `./${scope}.json`.fullname(dir);
116
+ this.log('info', `文件路径设置为: ${this.file_path}`);
117
+ };
89
118
 
119
+ /**
120
+ * 初始化服务
121
+ * @private
122
+ * @returns {Promise<void>}
123
+ */
124
+ CacheBase.prototype._initService = async function () {
125
+ try {
126
+ // 设置文件路径
127
+ this._setFilePath();
90
128
  // 初始化过期检查定时器
91
129
  this._check_timer = setInterval(() => {
92
130
  this.clearExpire();
@@ -114,7 +152,7 @@ CacheBase.prototype._initService = async function() {
114
152
  * 设置定时保存(内部方法)
115
153
  * @private
116
154
  */
117
- CacheBase.prototype._connect = function() {
155
+ CacheBase.prototype._connect = function () {
118
156
  // 如果启用了自动保存
119
157
  if (this.config.auto_save) {
120
158
  this._save_timer = setInterval(() => {
@@ -127,17 +165,15 @@ CacheBase.prototype._connect = function() {
127
165
  * 从文件加载数据
128
166
  * @private
129
167
  */
130
- CacheBase.prototype._loadData = function() {
168
+ CacheBase.prototype._loadData = function () {
131
169
  try {
132
- if (this.config.persist && this.config.file_path) {
133
- // 使用字符串的原型函数获取完整路径
134
- const file_path = this.config.file_path.fullname();
135
- this.log('info', `[_loadData] 尝试加载文件: ${file_path}`);
170
+ if (this.config.persist && this.file_path) {
171
+ this.log('info', `[_loadData] 尝试加载文件: ${this.file_path}`);
136
172
 
137
- if (file_path.hasFile()) {
173
+ if (this.file_path.hasFile()) {
138
174
  this.log('info', `[_loadData] 文件存在,开始读取`);
139
175
  // 使用mm_expand的原型函数读取JSON文件
140
- const parsed_data = file_path.loadJson();
176
+ const parsed_data = this.file_path.loadJson();
141
177
  this.log('info', `[_loadData] 文件读取成功,解析后的数据:`, Object.keys(parsed_data || {}));
142
178
 
143
179
  if (parsed_data && parsed_data.data) {
@@ -155,7 +191,7 @@ CacheBase.prototype._loadData = function() {
155
191
  this._types = parsed_data.types || {};
156
192
  }
157
193
  } else {
158
- this.log('info', `[_loadData] 文件不存在: ${file_path}`);
194
+ this.log('info', `[_loadData] 文件不存在: ${this.file_path}`);
159
195
  }
160
196
  } else {
161
197
  this.log('info', `[_loadData] 持久化未启用或文件路径未设置`);
@@ -168,7 +204,7 @@ CacheBase.prototype._loadData = function() {
168
204
  /**
169
205
  * 保存数据到文件
170
206
  */
171
- CacheBase.prototype.save = function() {
207
+ CacheBase.prototype.save = function () {
172
208
  // 检查服务状态
173
209
  if (!this.is_inited || this.is_destroyed) {
174
210
  this.log('error', 'Service is not initialized or has been destroyed');
@@ -188,14 +224,11 @@ CacheBase.prototype.save = function() {
188
224
  * 保存数据到文件
189
225
  * @private
190
226
  */
191
- CacheBase.prototype._saveData = function() {
227
+ CacheBase.prototype._saveData = function () {
192
228
  try {
193
- if (this.config.persist && this.config.file_path) {
194
- // 使用字符串的原型函数获取完整路径
195
- const file_path = this.config.file_path.fullname();
196
-
229
+ if (this.config.persist && this.file_path) {
197
230
  // 确保目录存在 - 使用目录路径的原型函数
198
- file_path.addDir();
231
+ this.file_path.addDir();
199
232
 
200
233
  const data_to_save = {
201
234
  data: this._data,
@@ -205,7 +238,7 @@ CacheBase.prototype._saveData = function() {
205
238
  };
206
239
 
207
240
  // 使用mm_expand的原型函数写入JSON文件
208
- file_path.saveJson(data_to_save, null, 2);
241
+ this.file_path.saveJson(data_to_save, null, 2);
209
242
  }
210
243
  } catch (error) {
211
244
  this.log('error', 'Failed to save data:', error);
@@ -216,14 +249,11 @@ CacheBase.prototype._saveData = function() {
216
249
  * 销毁服务
217
250
  * @returns {Promise<void>}
218
251
  */
219
- CacheBase.prototype.destroy = async function() {
252
+ CacheBase.prototype.destroy = async function () {
220
253
  if (this.is_destroyed) {
221
254
  return;
222
255
  }
223
256
 
224
- // 调用父类destroy方法处理通用销毁逻辑
225
- await BaseService.prototype.destroy.call(this);
226
-
227
257
  try {
228
258
  // 保存数据
229
259
  this.save();
@@ -255,6 +285,14 @@ CacheBase.prototype.destroy = async function() {
255
285
  }
256
286
  };
257
287
 
288
+ /**
289
+ * 关闭缓存服务(兼容方法)
290
+ * @returns {Promise<void>}
291
+ */
292
+ CacheBase.prototype.close = function () {
293
+ return this.destroy();
294
+ };
295
+
258
296
  /**
259
297
  * 设置键值对
260
298
  * @param {string} key - 键名
@@ -262,7 +300,7 @@ CacheBase.prototype.destroy = async function() {
262
300
  * @param {number} [ttl] - 过期时间(秒)
263
301
  * @returns {boolean} 操作结果
264
302
  */
265
- CacheBase.prototype.set = function(key, value, ttl) {
303
+ CacheBase.prototype.set = function (key, value, ttl) {
266
304
  // 检查服务状态
267
305
  if (!this.is_inited || this.is_destroyed) {
268
306
  this.log('error', 'Service is not initialized or has been destroyed');
@@ -323,7 +361,7 @@ CacheBase.prototype.set = function(key, value, ttl) {
323
361
  * @param {string} key - 键
324
362
  * @returns {*} 值
325
363
  */
326
- CacheBase.prototype.get = function(key) {
364
+ CacheBase.prototype.get = function (key) {
327
365
  // 检查服务状态
328
366
  if (!this.is_inited || this.is_destroyed) {
329
367
  this.log('error', 'Service is not initialized or has been destroyed');
@@ -349,7 +387,7 @@ CacheBase.prototype.get = function(key) {
349
387
  * @param {string|Array<string>} key - 键名或键名数组
350
388
  * @returns {boolean} 是否成功删除
351
389
  */
352
- CacheBase.prototype.del = function(key) {
390
+ CacheBase.prototype.del = function (key) {
353
391
  // 参数验证
354
392
  if (!key) {
355
393
  throw new TypeError('key必须是非空字符串或非空字符串数组');
@@ -437,7 +475,7 @@ CacheBase.prototype.del = function(key) {
437
475
  * @param {Array} keys - 键名数组
438
476
  * @returns {number} 删除的键数量
439
477
  */
440
- CacheBase.prototype.delBatch = function(keys) {
478
+ CacheBase.prototype.delBatch = function (keys) {
441
479
  try {
442
480
  if (!Array.isArray(keys)) {
443
481
  return 0;
@@ -462,7 +500,7 @@ CacheBase.prototype.delBatch = function(keys) {
462
500
  * @param {string} key - 键
463
501
  * @returns {boolean} 存在状态
464
502
  */
465
- CacheBase.prototype.exists = function(key) {
503
+ CacheBase.prototype.exists = function (key) {
466
504
  try {
467
505
  if (this._isExpired(key)) {
468
506
  this.del(key);
@@ -481,14 +519,14 @@ CacheBase.prototype.exists = function(key) {
481
519
  * @param {string} key - 键名
482
520
  * @returns {boolean} 是否存在
483
521
  */
484
- CacheBase.prototype.has = function(key) {
522
+ CacheBase.prototype.has = function (key) {
485
523
  return this.exists(key);
486
524
  };
487
525
 
488
526
  /**
489
527
  * 清空过期数据
490
528
  */
491
- CacheBase.prototype.clearExpire = function() {
529
+ CacheBase.prototype.clearExpire = function () {
492
530
  try {
493
531
  const now = Date.now();
494
532
  for (const key in this._expires) {
@@ -507,7 +545,7 @@ CacheBase.prototype.clearExpire = function() {
507
545
  * @param {string} key - 键名
508
546
  * @returns {boolean} 是否过期
509
547
  */
510
- CacheBase.prototype._isExpired = function(key) {
548
+ CacheBase.prototype._isExpired = function (key) {
511
549
  // 先检查键是否存在
512
550
  if (!(key in this._data)) {
513
551
  return true;
@@ -537,7 +575,7 @@ CacheBase.prototype._isExpired = function(key) {
537
575
  * @param {*} value - 值
538
576
  * @returns {string} 数据类型
539
577
  */
540
- CacheBase.prototype._getDataTypes = function(value) {
578
+ CacheBase.prototype._getDataTypes = function (value) {
541
579
  if (value === null) return 'null';
542
580
  if (Array.isArray(value)) return 'array';
543
581
  return typeof value;
@@ -549,7 +587,7 @@ CacheBase.prototype._getDataTypes = function(value) {
549
587
  * @param {number} seconds - 过期时间(秒)
550
588
  * @returns {boolean} 是否成功
551
589
  */
552
- CacheBase.prototype.expire = function(key, seconds) {
590
+ CacheBase.prototype.expire = function (key, seconds) {
553
591
  try {
554
592
  // 参数验证
555
593
  if (!key || typeof key !== 'string') {
@@ -601,7 +639,7 @@ CacheBase.prototype.expire = function(key, seconds) {
601
639
  * @param {*} value - 值
602
640
  * @returns {number} 1表示新增,0表示更新或失败
603
641
  */
604
- CacheBase.prototype.hset = function(key, field, value) {
642
+ CacheBase.prototype.hset = function (key, field, value) {
605
643
  try {
606
644
  // 参数验证
607
645
  if (!key || typeof key !== 'string' || !field || typeof field !== 'string') {
@@ -657,7 +695,7 @@ CacheBase.prototype.hset = function(key, field, value) {
657
695
  * @param {string} field - 字段名
658
696
  * @returns {*} 字段值
659
697
  */
660
- CacheBase.prototype.hget = function(key, field) {
698
+ CacheBase.prototype.hget = function (key, field) {
661
699
  try {
662
700
  // 参数验证
663
701
  if (!key || typeof key !== 'string' || !field || typeof field !== 'string') {
@@ -685,7 +723,7 @@ CacheBase.prototype.hget = function(key, field) {
685
723
  * 清空所有数据
686
724
  * @returns {boolean} 操作结果
687
725
  */
688
- CacheBase.prototype.clear = function() {
726
+ CacheBase.prototype.clear = function () {
689
727
  return this.flushdb();
690
728
  };
691
729
 
@@ -694,7 +732,7 @@ CacheBase.prototype.clear = function() {
694
732
  * @param {string} key - 哈希表键名
695
733
  * @returns {Object} 哈希表内容
696
734
  */
697
- CacheBase.prototype.hgetall = function(key) {
735
+ CacheBase.prototype.hgetall = function (key) {
698
736
  try {
699
737
  // 参数验证
700
738
  if (!key || typeof key !== 'string') {
@@ -728,7 +766,7 @@ CacheBase.prototype.hgetall = function(key) {
728
766
  * @param {string|Array<string>} field - 字段名或字段名数组
729
767
  * @returns {boolean} 删除成功返回true,失败返回false
730
768
  */
731
- CacheBase.prototype.hdel = function(key, field) {
769
+ CacheBase.prototype.hdel = function (key, field) {
732
770
  try {
733
771
  // 参数验证
734
772
  if (!key || typeof key !== 'string') {
@@ -812,7 +850,7 @@ CacheBase.prototype.hdel = function(key, field) {
812
850
  * @param {number} value - 增加的值(默认为1)
813
851
  * @returns {number} 增加后的值
814
852
  */
815
- CacheBase.prototype.incrby = function(key, value) {
853
+ CacheBase.prototype.incrby = function (key, value) {
816
854
  // 参数验证
817
855
  if (!key || typeof key !== 'string' || typeof value !== 'number') {
818
856
  return 0;
@@ -856,7 +894,7 @@ CacheBase.prototype.incrby = function(key, value) {
856
894
  * @param {number} seconds - 过期时间(秒),0表示永不过期
857
895
  * @returns {number|null} 增加后的值,失败返回null
858
896
  */
859
- CacheBase.prototype.incr = function(key, seconds = 0) {
897
+ CacheBase.prototype.incr = function (key, seconds = 0) {
860
898
  try {
861
899
  // 参数验证
862
900
  if (!key || typeof key !== 'string') {
@@ -912,7 +950,7 @@ CacheBase.prototype.incr = function(key, seconds = 0) {
912
950
  }
913
951
  };
914
952
 
915
- CacheBase.prototype.decrby = function(key, value) {
953
+ CacheBase.prototype.decrby = function (key, value) {
916
954
  // 参数验证
917
955
  if (!key || typeof key !== 'string' || typeof value !== 'number') {
918
956
  return 0;
@@ -956,7 +994,7 @@ CacheBase.prototype.decrby = function(key, value) {
956
994
  * @param {number} seconds - 过期时间(秒),0表示永不过期
957
995
  * @returns {number} 减少后的值
958
996
  */
959
- CacheBase.prototype.decr = function(key, seconds = 0) {
997
+ CacheBase.prototype.decr = function (key, seconds = 0) {
960
998
  try {
961
999
  // 参数验证
962
1000
  if (!key || typeof key !== 'string') {
@@ -1019,7 +1057,7 @@ CacheBase.prototype.decr = function(key, seconds = 0) {
1019
1057
  * @param {number} seconds - 过期时间(秒),0表示永不过期
1020
1058
  * @returns {Promise<number>} - 返回增加后的值
1021
1059
  */
1022
- CacheBase.prototype.addInt = function(key, value, seconds = 0) {
1060
+ CacheBase.prototype.addInt = function (key, value, seconds = 0) {
1023
1061
  // 参数验证
1024
1062
  if (!key || typeof key !== 'string') {
1025
1063
  throw new TypeError('key必须是非空字符串');
@@ -1027,7 +1065,7 @@ CacheBase.prototype.addInt = function(key, value, seconds = 0) {
1027
1065
  if (typeof value !== 'number') {
1028
1066
  throw new TypeError('value必须是数字');
1029
1067
  }
1030
-
1068
+
1031
1069
  try {
1032
1070
 
1033
1071
  this.emit('addInt_before', {
@@ -1080,7 +1118,7 @@ CacheBase.prototype.addInt = function(key, value, seconds = 0) {
1080
1118
  * @param {string} append - 要追加的内容
1081
1119
  * @returns {number|null} 追加后的字符串长度,失败返回null
1082
1120
  */
1083
- CacheBase.prototype.append = function(key, append) {
1121
+ CacheBase.prototype.append = function (key, append) {
1084
1122
  try {
1085
1123
  // 参数验证
1086
1124
  if (!key || typeof key !== 'string' || typeof append !== 'string') {
@@ -1118,7 +1156,7 @@ CacheBase.prototype.append = function(key, append) {
1118
1156
  * @param {string} key - 键名
1119
1157
  * @returns {number} 字符串长度,不存在返回0
1120
1158
  */
1121
- CacheBase.prototype.strlen = function(key) {
1159
+ CacheBase.prototype.strlen = function (key) {
1122
1160
  try {
1123
1161
  // 参数验证
1124
1162
  if (!key || typeof key !== 'string') {
@@ -1152,7 +1190,7 @@ CacheBase.prototype.strlen = function(key) {
1152
1190
  * 清空所有数据库键
1153
1191
  * @returns {boolean} 操作结果
1154
1192
  */
1155
- CacheBase.prototype.flushdb = function() {
1193
+ CacheBase.prototype.flushdb = function () {
1156
1194
  try {
1157
1195
  // 触发操作前事件
1158
1196
  const event_data = {
@@ -1185,7 +1223,7 @@ CacheBase.prototype.flushdb = function() {
1185
1223
  * @param {string} [pattern] - 键名匹配模式,支持*通配符
1186
1224
  * @returns {Array} 所有键名数组
1187
1225
  */
1188
- CacheBase.prototype.keys = function(pattern) {
1226
+ CacheBase.prototype.keys = function (pattern) {
1189
1227
  try {
1190
1228
  const result = [];
1191
1229
  for (const key in this._data) {
@@ -1211,7 +1249,7 @@ CacheBase.prototype.keys = function(pattern) {
1211
1249
  * @param {string} pattern - 匹配模式,支持*通配符
1212
1250
  * @returns {boolean} 是否匹配
1213
1251
  */
1214
- CacheBase.prototype._matchPattern = function(key, pattern) {
1252
+ CacheBase.prototype._matchPattern = function (key, pattern) {
1215
1253
  // 将模式转换为正则表达式
1216
1254
  try {
1217
1255
  var regexPattern = pattern
@@ -1229,7 +1267,7 @@ CacheBase.prototype._matchPattern = function(key, pattern) {
1229
1267
  * 获取键的数量
1230
1268
  * @returns {number} 键的数量
1231
1269
  */
1232
- CacheBase.prototype.dbsize = function() {
1270
+ CacheBase.prototype.dbsize = function () {
1233
1271
  try {
1234
1272
  // 计算未过期的键数量
1235
1273
  let count = 0;
@@ -1252,7 +1290,7 @@ CacheBase.prototype.dbsize = function() {
1252
1290
  * @param {number} seconds - 过期时间(秒),0表示永不过期
1253
1291
  * @returns {number} 增加后的值,失败返回0
1254
1292
  */
1255
- CacheBase.prototype.incrbyfloat = function(key, value = 1.0, seconds = 0) {
1293
+ CacheBase.prototype.incrbyfloat = function (key, value = 1.0, seconds = 0) {
1256
1294
  try {
1257
1295
  // 参数验证
1258
1296
  if (!key || typeof key !== 'string' || typeof value !== 'number') {
@@ -1318,7 +1356,7 @@ CacheBase.prototype.incrbyfloat = function(key, value = 1.0, seconds = 0) {
1318
1356
  * @param {number} expire - 过期时间(毫秒)
1319
1357
  * @returns {*} 旧值
1320
1358
  */
1321
- CacheBase.prototype.getset = function(key, value, expire) {
1359
+ CacheBase.prototype.getset = function (key, value, expire) {
1322
1360
  try {
1323
1361
  // 参数验证
1324
1362
  if (!key || typeof key !== 'string') {
@@ -1345,7 +1383,7 @@ CacheBase.prototype.getset = function(key, value, expire) {
1345
1383
  * @param {number} maxAge - 过期时间(秒),0表示永不过期
1346
1384
  * @returns {Promise<boolean>} - 操作结果,键不存在并设置成功返回true,键已存在返回false
1347
1385
  */
1348
- CacheBase.prototype.add = function(key, value, maxAge = 0) {
1386
+ CacheBase.prototype.add = function (key, value, maxAge = 0) {
1349
1387
  try {
1350
1388
  // 参数验证
1351
1389
  if (!key || typeof key !== 'string') {
@@ -1403,7 +1441,7 @@ CacheBase.prototype.add = function(key, value, maxAge = 0) {
1403
1441
  success: true
1404
1442
  });
1405
1443
  return true;
1406
- } catch (error) {
1444
+ } catch (error) {
1407
1445
  this.log('error', `add操作失败 [${key}]:`, error);
1408
1446
  this.emit('add_error', {
1409
1447
  key,
@@ -1422,7 +1460,7 @@ CacheBase.prototype.add = function(key, value, maxAge = 0) {
1422
1460
  * @param {number} seconds - 过期时间(秒),0表示永不过期
1423
1461
  * @returns {Promise<number>} - 返回增加后的值
1424
1462
  */
1425
- CacheBase.prototype.addFloat = function(key, num, seconds = 0) {
1463
+ CacheBase.prototype.addFloat = function (key, num, seconds = 0) {
1426
1464
  try {
1427
1465
  // 参数验证
1428
1466
  if (!key || typeof key !== 'string' || typeof num !== 'number') {
@@ -1480,7 +1518,7 @@ CacheBase.prototype.addFloat = function(key, num, seconds = 0) {
1480
1518
  * @param {number} seconds - 过期时间(秒),0表示永不过期
1481
1519
  * @returns {Promise<number>} - 返回追加后字符串的长度
1482
1520
  */
1483
- CacheBase.prototype.addStr = function(key, value, seconds = 0) {
1521
+ CacheBase.prototype.addStr = function (key, value, seconds = 0) {
1484
1522
  try {
1485
1523
  // 参数验证
1486
1524
  if (!key || typeof key !== 'string' || typeof value !== 'string') {
@@ -1538,7 +1576,7 @@ CacheBase.prototype.addStr = function(key, value, seconds = 0) {
1538
1576
  * @param {string} key1, value1, key2, value2... - 键值对参数列表
1539
1577
  * @returns {boolean} - 成功返回true,失败返回false
1540
1578
  */
1541
- CacheBase.prototype.mset = function(...args) {
1579
+ CacheBase.prototype.mset = function (...args) {
1542
1580
  try {
1543
1581
  // 参数验证 - 特别处理null参数情况
1544
1582
  if (args.length === 1 && args[0] === null) {
@@ -1618,7 +1656,7 @@ CacheBase.prototype.mset = function(...args) {
1618
1656
  * @param {Number} [seconds] 过期时间(秒),不传此参数则获取剩余过期时间
1619
1657
  * @return {Promise<Number|Boolean>} 不传seconds时返回剩余过期时间(-1表示无过期设置,-2表示已过期),传seconds时返回是否设置成功
1620
1658
  */
1621
- CacheBase.prototype.ttl = function(key, seconds) {
1659
+ CacheBase.prototype.ttl = function (key, seconds) {
1622
1660
  try {
1623
1661
  // 参数验证
1624
1662
  if (!key || typeof key !== 'string') {
@@ -1677,12 +1715,12 @@ CacheBase.prototype.ttl = function(key, seconds) {
1677
1715
  return Math.max(0, Math.ceil(remaining / 1000));
1678
1716
  }
1679
1717
  } catch (error) {
1680
- const errorMsg = arguments.length > 1 && seconds !== undefined
1681
- ? `Failed to set ttl for key ${key}: ${error.message}`
1682
- : `Failed to get ttl for key ${key}: ${error.message}`;
1683
- this.log('error', errorMsg, error);
1684
- return arguments.length > 1 && seconds !== undefined ? false : -2;
1685
- }
1718
+ const errorMsg = arguments.length > 1 && seconds !== undefined
1719
+ ? `Failed to set ttl for key ${key}: ${error.message}`
1720
+ : `Failed to get ttl for key ${key}: ${error.message}`;
1721
+ this.log('error', errorMsg, error);
1722
+ return arguments.length > 1 && seconds !== undefined ? false : -2;
1723
+ }
1686
1724
  };
1687
1725
 
1688
1726
  /**
@@ -1690,7 +1728,7 @@ CacheBase.prototype.ttl = function(key, seconds) {
1690
1728
  * @param {string} key - 键名
1691
1729
  * @returns {boolean} 是否成功移除
1692
1730
  */
1693
- CacheBase.prototype.persist = function(key) {
1731
+ CacheBase.prototype.persist = function (key) {
1694
1732
  try {
1695
1733
  // 参数验证
1696
1734
  if (!key || typeof key !== 'string') {
@@ -1741,7 +1779,7 @@ CacheBase.prototype.persist = function(key) {
1741
1779
  * @param {Array} keys - 键名数组
1742
1780
  * @returns {Array} 值数组,按键的顺序返回
1743
1781
  */
1744
- CacheBase.prototype.mget = function(keys) {
1782
+ CacheBase.prototype.mget = function (keys) {
1745
1783
  try {
1746
1784
  // 参数验证
1747
1785
  if (!Array.isArray(keys)) {
@@ -1770,7 +1808,7 @@ CacheBase.prototype.mget = function(keys) {
1770
1808
  * 清理资源并销毁实例
1771
1809
  * @returns {boolean} 操作结果
1772
1810
  */
1773
- CacheBase.prototype.dispose = function() {
1811
+ CacheBase.prototype.dispose = function () {
1774
1812
  try {
1775
1813
  // 清除定时任务
1776
1814
  if (this._auto_save_timer) {
@@ -1799,11 +1837,11 @@ CacheBase.prototype.dispose = function() {
1799
1837
  * 确保连接池对象存在
1800
1838
  */
1801
1839
  global.$ = global.$ || {};
1802
- if (!global.$.pool) {
1803
- global.$.pool = {};
1840
+ if (!$.pool) {
1841
+ $.pool = {};
1804
1842
  }
1805
- if (!global.$.pool.cachebase) {
1806
- global.$.pool.cachebase = {};
1843
+ if (!$.pool.cachebase) {
1844
+ $.pool.cachebase = {};
1807
1845
  }
1808
1846
 
1809
1847
  /**
@@ -1816,13 +1854,13 @@ function cachebase_admin(scope, dir) {
1816
1854
  if (!scope) {
1817
1855
  scope = 'sys';
1818
1856
  }
1819
- var obj = global.$.pool.cachebase[scope];
1857
+ var obj = $.pool.cachebase[scope];
1820
1858
  if (!obj) {
1821
1859
  const config = {
1822
1860
  file_path: dir ? `./cachebase_${scope}.json`.fullname(dir) : `/cache/cachebase_${scope}.json`
1823
1861
  };
1824
- global.$.pool.cachebase[scope] = new CacheBase(config);
1825
- obj = global.$.pool.cachebase[scope];
1862
+ $.pool.cachebase[scope] = new CacheBase(config);
1863
+ obj = $.pool.cachebase[scope];
1826
1864
  }
1827
1865
  return obj;
1828
1866
  }
@@ -1834,7 +1872,7 @@ function cachebase_admin(scope, dir) {
1834
1872
  * @param {number} [maxAge=0] - 过期时间(秒),0表示永不过期
1835
1873
  * @returns {Promise<number>} - 列表长度
1836
1874
  */
1837
- CacheBase.prototype.setForList = async function(key, value, maxAge = 0) {
1875
+ CacheBase.prototype.setForList = async function (key, value, maxAge = 0) {
1838
1876
  try {
1839
1877
  // 参数验证
1840
1878
  if (!key || typeof key !== 'string') {
@@ -1914,7 +1952,7 @@ CacheBase.prototype.setForList = async function(key, value, maxAge = 0) {
1914
1952
  * @param {number} [maxAge=0] - 过期时间(秒),0表示永不过期
1915
1953
  * @returns {Promise<number>} - 添加后列表长度
1916
1954
  */
1917
- CacheBase.prototype.addForList = async function(key, value, maxAge = 0) {
1955
+ CacheBase.prototype.addForList = async function (key, value, maxAge = 0) {
1918
1956
  try {
1919
1957
  // 参数验证
1920
1958
  if (!key || typeof key !== 'string') {
@@ -1990,7 +2028,7 @@ CacheBase.prototype.addForList = async function(key, value, maxAge = 0) {
1990
2028
  * @param {*} value - 要检查的元素
1991
2029
  * @returns {Promise<boolean>} - 是否包含
1992
2030
  */
1993
- CacheBase.prototype.hasForList = async function(key, value) {
2031
+ CacheBase.prototype.hasForList = async function (key, value) {
1994
2032
  try {
1995
2033
  // 参数验证
1996
2034
  if (!key || typeof key !== 'string') {
@@ -2055,7 +2093,7 @@ CacheBase.prototype.hasForList = async function(key, value) {
2055
2093
  * @param {number} [stop=-1] - 结束索引,-1表示全部
2056
2094
  * @returns {Promise<Array>} - 列表数组
2057
2095
  */
2058
- CacheBase.prototype.getForList = async function(key, start = 0, stop = -1) {
2096
+ CacheBase.prototype.getForList = async function (key, start = 0, stop = -1) {
2059
2097
  try {
2060
2098
  // 参数验证
2061
2099
  if (!key || typeof key !== 'string') {
@@ -2126,7 +2164,7 @@ CacheBase.prototype.getForList = async function(key, start = 0, stop = -1) {
2126
2164
  * @param {string} key - 键名
2127
2165
  * @returns {Promise<boolean>} - 操作结果
2128
2166
  */
2129
- CacheBase.prototype.clearForList = async function(key) {
2167
+ CacheBase.prototype.clearForList = async function (key) {
2130
2168
  try {
2131
2169
  // 参数验证
2132
2170
  if (!key || typeof key !== 'string') {
@@ -2200,7 +2238,7 @@ CacheBase.prototype.clearForList = async function(key) {
2200
2238
  * @param {Object} obj - 包含多个字段的对象
2201
2239
  * @returns {Promise<boolean>} - 操作结果
2202
2240
  */
2203
- CacheBase.prototype.hmset = function(key, obj) {
2241
+ CacheBase.prototype.hmset = function (key, obj) {
2204
2242
  return new Promise((resolve) => {
2205
2243
  try {
2206
2244
  // 参数验证
@@ -2265,7 +2303,7 @@ CacheBase.prototype.hmset = function(key, obj) {
2265
2303
  * @param {Array} fields - 字段名数组
2266
2304
  * @returns {Promise<Array>} - 字段值数组,不存在的字段返回null
2267
2305
  */
2268
- CacheBase.prototype.hmget = function(key, fields) {
2306
+ CacheBase.prototype.hmget = function (key, fields) {
2269
2307
  return new Promise((resolve) => {
2270
2308
  try {
2271
2309
  // 参数验证
@@ -2311,7 +2349,7 @@ CacheBase.prototype.hmget = function(key, fields) {
2311
2349
  * @param {string} key - 哈希表键名
2312
2350
  * @returns {Promise<number>} - 字段数量,失败返回0
2313
2351
  */
2314
- CacheBase.prototype.hlen = function(key) {
2352
+ CacheBase.prototype.hlen = function (key) {
2315
2353
  return new Promise((resolve) => {
2316
2354
  try {
2317
2355
  // 参数验证
@@ -2356,23 +2394,23 @@ function cachebaseAdmin(scope, config) {
2356
2394
  if (!global.$) {
2357
2395
  global.$ = {};
2358
2396
  }
2359
- if (!global.$.pool) {
2360
- global.$.pool = {};
2397
+ if (!$.pool) {
2398
+ $.pool = {};
2361
2399
  }
2362
- if (!global.$.pool.cachebase) {
2363
- global.$.pool.cachebase = {};
2400
+ if (!$.pool.cachebase) {
2401
+ $.pool.cachebase = {};
2364
2402
  }
2365
2403
  if (!scope) {
2366
2404
  scope = 'sys';
2367
2405
  }
2368
- var obj = global.$.pool.cachebase[scope];
2406
+ var obj = $.pool.cachebase[scope];
2369
2407
  if (!obj) {
2370
2408
  const dbConfig = {
2371
- file_path: config && config.dir ? config.dir + '/' + scope + '.json' : '/cache/' + scope + '.json',
2409
+ scope: scope,
2372
2410
  ...(typeof config === 'object' && config ? config : {})
2373
2411
  };
2374
- global.$.pool.cachebase[scope] = new CacheBase(dbConfig);
2375
- obj = global.$.pool.cachebase[scope];
2412
+ $.pool.cachebase[scope] = new CacheBase(dbConfig);
2413
+ obj = $.pool.cachebase[scope];
2376
2414
  }
2377
2415
  return obj;
2378
2416
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mm_cachebase",
3
- "version": "1.9.4",
3
+ "version": "1.9.6",
4
4
  "description": "一个轻量级的本地缓存类库,提供与Redis兼容的API接口,支持过期时间设置、哈希表操作、数值操作、字符串操作等功能,以及完整的事件通知系统和多文件持久化功能。",
5
5
  "main": "index.js",
6
6
  "scripts": {
package/test.js CHANGED
@@ -1,3 +1,4 @@
1
+ const assert = require('assert');
1
2
  const { CacheBase, cachebaseAdmin } = require('./index.js');
2
3
 
3
4
  class TestRunner {
@@ -50,16 +51,24 @@ async function test() {
50
51
  $.log.debug('[CacheBase] \n========== 测试基础方法 ==========');
51
52
 
52
53
  await runner.runTest('set和get方法', async () => {
53
- const cache = new CacheBase({ file_path: './test_cache/test_set_get.cache.json' });
54
- await cache.set('key1', 'value1');
55
- const value = await cache.get('key1');
56
- if (value !== 'value1') {
57
- throw new Error(`预期值: value1, 实际值: ${value}`);
58
- }
59
- });
54
+ const cache = new CacheBase({ scope: 'test_set_get' });
55
+ await cache.init();
56
+
57
+ await cache.set('test_key', 'test_value');
58
+ const value = await cache.get('test_key');
59
+
60
+ assert.equal(value, 'test_value', 'set和get方法测试失败');
61
+
62
+ await cache.del('test_key');
63
+ const deleted_value = await cache.get('test_key');
64
+
65
+ assert.equal(deleted_value, null, 'del方法测试失败');
66
+
67
+ await cache.close();
68
+ });
60
69
 
61
70
  await runner.runTest('del方法', async () => {
62
- const cache = new CacheBase({ file_path: './test_cache/test_del.cache.json' });
71
+ const cache = new CacheBase({ scope: 'test_del' });
63
72
  await cache.set('key2', 'value2');
64
73
  const deleted = await cache.del('key2');
65
74
  if (deleted !== true) {
@@ -72,7 +81,7 @@ async function test() {
72
81
  });
73
82
 
74
83
  await runner.runTest('exists/has方法', async () => {
75
- const cache = new CacheBase({ file_path: './test_cache/test_exists_has.cache.json' });
84
+ const cache = new CacheBase({ scope: 'test_exists_has' });
76
85
  await cache.set('key3', 'value3');
77
86
  const exists = await cache.exists('key3');
78
87
  if (exists !== true) {
@@ -87,7 +96,7 @@ async function test() {
87
96
  await runner.runTest('keys方法', async () => {
88
97
  const cache = new CacheBase({
89
98
  persist: true,
90
- file_path: './test_cache/test_keys.cache.json'
99
+ scope: 'test_keys'
91
100
  });
92
101
  await cache.set('key4', 'value4');
93
102
  await cache.set('key5', 'value5');
@@ -104,7 +113,7 @@ async function test() {
104
113
  await runner.runTest('dbsize方法', async () => {
105
114
  const cache = new CacheBase({
106
115
  persist: true,
107
- file_path: './test_cache/test_dbsize.cache.json'
116
+ scope: 'test_dbsize'
108
117
  });
109
118
  await cache.set('key4', 'value4');
110
119
  await cache.set('key5', 'value5');
@@ -115,7 +124,7 @@ async function test() {
115
124
  });
116
125
 
117
126
  await runner.runTest('getset方法', async () => {
118
- const cache = new CacheBase({ file_path: './test_cache/test_getset.cache.json' });
127
+ const cache = new CacheBase({ scope: 'test_getset' });
119
128
  await cache.set('key4', 'value4');
120
129
  const oldValue = await cache.getset('key4', 'newvalue4');
121
130
  if (oldValue !== 'value4') {
@@ -130,7 +139,7 @@ async function test() {
130
139
  await runner.runTest('flushdb/clear方法', async () => {
131
140
  const cache = new CacheBase({
132
141
  persist: true,
133
- file_path: './test_cache/test_flushdb.cache.json'
142
+ scope: 'test_flushdb'
134
143
  });
135
144
  await cache.set('key6', 'value6');
136
145
  let result = await cache.clear();
@@ -156,7 +165,7 @@ async function test() {
156
165
 
157
166
  // 测试哈希表方法
158
167
  $.log.debug('[CacheBase] \n========== 测试哈希表方法 ==========');
159
- const hashCache = new CacheBase({ file_path: './test_cache/test_hash.cache.json' });
168
+ const hashCache = new CacheBase({ scope: 'test_hash' });
160
169
 
161
170
  await runner.runTest('hset和hget方法', async () => {
162
171
  const result1 = await hashCache.hset('hash1', 'field1', 'value1');
@@ -202,7 +211,7 @@ async function test() {
202
211
 
203
212
  // 测试批量操作
204
213
  $.log.debug('[CacheBase] \n========== 测试批量操作 ==========');
205
- const batchCache = new CacheBase({ file_path: './test_cache/test_batch.cache.json' });
214
+ const batchCache = new CacheBase({ scope: 'test_batch' });
206
215
 
207
216
  await runner.runTest('mset方法', async () => {
208
217
  const result = await batchCache.mset('key7', 'value7', 'key8', 'value8');
@@ -225,7 +234,7 @@ async function test() {
225
234
 
226
235
  // 测试过期时间
227
236
  $.log.debug('[CacheBase] \n========== 测试过期时间 ==========');
228
- const expireCache = new CacheBase({ file_path: './test_cache/test_expire.cache.json' });
237
+ const expireCache = new CacheBase({ scope: 'test_expire' });
229
238
 
230
239
  await runner.runTest('set带过期时间', async () => {
231
240
  await expireCache.set('expire1', 'value1', 1); // 1秒过期
@@ -274,7 +283,7 @@ async function test() {
274
283
 
275
284
  // 测试数值操作
276
285
  $.log.debug('[CacheBase] \n========== 测试数值操作 ==========');
277
- const numCache = new CacheBase({ file_path: './test_cache/test_num.cache.json' });
286
+ const numCache = new CacheBase({ scope: 'test_num' });
278
287
 
279
288
  await runner.runTest('incr方法', async () => {
280
289
  const result1 = await numCache.incr('counter');
@@ -376,7 +385,7 @@ async function test() {
376
385
 
377
386
  // 测试字符串操作
378
387
  $.log.debug('[CacheBase] \n========== 测试字符串操作 ==========');
379
- const strCache = new CacheBase({ file_path: './test_cache/test_str.cache.json' });
388
+ const strCache = new CacheBase({ scope: 'test_str' });
380
389
 
381
390
  await runner.runTest('append方法', async () => {
382
391
  await strCache.set('str', 'hello');
@@ -416,7 +425,7 @@ async function test() {
416
425
 
417
426
  // 测试事件触发
418
427
  $.log.debug('[CacheBase] \n========== 测试事件触发 ==========');
419
- const eventCache = new CacheBase({ file_path: './test_cache/test_event.cache.json' });
428
+ const eventCache = new CacheBase({ scope: 'test_event' });
420
429
 
421
430
  await runner.runTest('set事件触发', async () => {
422
431
  return new Promise(async (resolve, reject) => {
@@ -487,7 +496,7 @@ async function test() {
487
496
  await runner.runTest('dispose方法', async () => {
488
497
  const disposeCache = new CacheBase({
489
498
  persist: true,
490
- file_path: './test_cache/test_dispose.cache.json'
499
+ scope: 'test_dispose'
491
500
  });
492
501
  await disposeCache.set('key_to_dispose', 'value');
493
502
  disposeCache.dispose();