mm_cachebase 1.9.3 → 1.9.5

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