@aomex/cache 3.30.7 → 3.30.8-alpha.131cf1c.0

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.
package/dist/index.js CHANGED
@@ -1,419 +1,333 @@
1
- // src/caching.ts
1
+ import { t as CacheAdapter } from "./cache-adapter-4n2JTK4Y.js";
2
2
  import { traceBlock } from "@aomex/async-trace";
3
-
4
- // src/cache-adapter.ts
5
- var CacheAdapter = class {
6
- async connect() {
7
- }
8
- };
9
-
3
+ import { Service, sleep } from "@aomex/common";
4
+ import { createHash } from "node:crypto";
10
5
  // src/caching.ts
11
- import { sleep } from "@aomex/common";
12
- var CACHING_TYPE = "_$caching_type$_";
13
- var CACHING_DATA = "_$caching_data$_";
6
+ const CACHING_TYPE = "_$caching_type$_";
7
+ const CACHING_DATA = "_$caching_data$_";
14
8
  var Caching = class {
15
- constructor(adapter) {
16
- this.adapter = adapter;
17
- }
18
- /**
19
- * 查看缓存是否存在
20
- */
21
- async exists(key) {
22
- await this.adapter.connect();
23
- return this.adapter.existsKey(key);
24
- }
25
- async get(key, defaultValue) {
26
- await this.adapter.connect();
27
- const result = await this.adapter.getValue(key);
28
- return this.decodeValue(result, defaultValue);
29
- }
30
- /**
31
- * 设置缓存。可以指定过期时间(毫秒)
32
- *
33
- * ```typescript
34
- * await cache.set('key', 'value');
35
- * await cache.set('key', 'value', 3600);
36
- * ```
37
- */
38
- async set(key, value, durationMs) {
39
- await this.adapter.connect();
40
- return this.adapter.setValue(key, this.encodeValue(value), durationMs);
41
- }
42
- /**
43
- * 设置缓存。如果缓存已经存在,则设置失败,返回`false`
44
- *
45
- * ```typescript
46
- * await cache.setNX('foo', 'bar'); // true
47
- * await cache.setNX('foo', 'baz'); // false
48
- * ```
49
- */
50
- async setNX(key, value, durationMs) {
51
- await this.adapter.connect();
52
- return this.adapter.setNotExistValue(key, this.encodeValue(value), durationMs);
53
- }
54
- /**
55
- * 将一个或多个值按顺序插入到列表头部。当 key 存在但不是列表类型时,返回一个错误。
56
- *
57
- * ```typescript
58
- * await cache.leftPush('foo', 'a'); // ['a']
59
- * await cache.leftPush('foo', 'b', 'c'); // ['b', 'c', 'a']
60
- * ```
61
- */
62
- async leftPush(key, ...values) {
63
- if (!values.length) return false;
64
- await this.adapter.connect();
65
- return this.adapter.leftPushValue(
66
- key,
67
- ...values.map((value) => this.encodeValue(value))
68
- );
69
- }
70
- /**
71
- * 移除列表的最后一个元素,返回值为被移除的元素
72
- */
73
- async rightPop(key) {
74
- await this.adapter.connect();
75
- const result = await this.adapter.rightPopValue(key);
76
- return this.decodeValue(result);
77
- }
78
- /**
79
- * 将key中储存的数字值增一。如果key不存在,那么key的值会先被初始化为0,然后再执行操作。如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。
80
- *
81
- * ```typescript
82
- * await cache.increment('foo'); // 1
83
- * await cache.increment('foo'); // 2
84
- * await cache.increment('foo'); // 3
85
- * ```
86
- */
87
- async increment(key) {
88
- await this.adapter.connect();
89
- return this.adapter.increaseValue(key);
90
- }
91
- /**
92
- * 重新设置缓存时间。如果key不存在,则返回`false`
93
- */
94
- async expire(key, durationMs) {
95
- await this.adapter.connect();
96
- return this.adapter.expireKey(key, durationMs);
97
- }
98
- /**
99
- * 检测缓存的剩余生存时间(Time to live)
100
- * - 不存在则返回`-2`
101
- * - 未设置过期时间则返回`-1`
102
- * - 已设置过期时间则返回剩余时间,单位**毫秒**
103
- *
104
- * ```typescript
105
- * await cache.ttl('foo'); // -2
106
- * await cache.set('foo', 'bar');
107
- * await cache.ttl('foo'); // -1
108
- * await cache.expire('foo', 60000);
109
- * await cache.ttl('foo'); // 59000
110
- * ```
111
- */
112
- async ttl(key) {
113
- await this.adapter.connect();
114
- return this.adapter.ttlKey(key);
115
- }
116
- /**
117
- * 将key中储存的数字值减一。如果key不存在,那么key的值会先被初始化为0,然后再执行操作。如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误
118
- */
119
- async decrement(key) {
120
- await this.adapter.connect();
121
- return this.adapter.decreaseValue(key);
122
- }
123
- /**
124
- * 删除指定缓存
125
- */
126
- async delete(key) {
127
- await this.adapter.connect();
128
- return this.adapter.deleteValue(key);
129
- }
130
- /**
131
- * 删除所有缓存
132
- */
133
- async deleteAll() {
134
- await this.adapter.connect();
135
- return this.adapter.deleteAllValues();
136
- }
137
- /**
138
- * 方法装饰器,自动获取数据,如果不存在则请求原始数据并自动保存。在请求原始数据期间,任意相同请求都会被截流,并共享第一个请求
139
- * ```typescript
140
- * const cache = new Caching(memoryAdapter());
141
- *
142
- * class MyClass {
143
- * \@cache.decorate({ key: (id) => `key_${id}`, duration: 60_000 })
144
- * async getData(id: number) {
145
- * const result = await queryDB({ id: id });
146
- * return result;
147
- * }
148
- * }
149
- * ```
150
- */
151
- decorate(opts) {
152
- const instance = this;
153
- const { key: getKey, duration, defaultValue = null } = opts;
154
- return (originalMethod, context) => {
155
- return async function(...args) {
156
- const dataKey = getKey === void 0 ? `${"displayName" in this && typeof this.displayName === "string" ? this.displayName : this.constructor.name}-${String(context.name)}-${JSON.stringify(args)}` : typeof getKey === "string" ? getKey : getKey.apply(this, args);
157
- const waitingKey = dataKey + ":$#_waiting_#$";
158
- const value = await traceBlock("Cache.get", () => instance.get(dataKey));
159
- if (value !== null) return value;
160
- const win = await instance.setNX(waitingKey, 1, 1e4);
161
- if (win) {
162
- const timer = setInterval(() => {
163
- instance.expire(waitingKey, 1e4);
164
- }, 5e3);
165
- try {
166
- const result = await traceBlock("Cache.exec", async () => {
167
- return originalMethod.apply(this, args);
168
- });
169
- if (result !== null) {
170
- await traceBlock("Cache.set", async () => {
171
- await instance.set(dataKey, result, duration);
172
- });
173
- }
174
- return result === null ? defaultValue : result;
175
- } finally {
176
- clearInterval(timer);
177
- await instance.delete(waitingKey);
178
- }
179
- } else {
180
- return traceBlock("Cache.wait", async () => {
181
- while (true) {
182
- const waiting = await instance.exists(waitingKey);
183
- if (waiting) {
184
- await sleep(100);
185
- continue;
186
- }
187
- return instance.get(dataKey, defaultValue);
188
- }
189
- });
190
- }
191
- };
192
- };
193
- }
194
- encodeValue(value) {
195
- if (value instanceof Date) {
196
- value = this.convertDate(value);
197
- }
198
- return JSON.stringify(value, (_, v) => this.stringifyReplacer(v));
199
- }
200
- stringifyReplacer(value) {
201
- if (value instanceof Map) {
202
- value = { [CACHING_TYPE]: "Map", [CACHING_DATA]: Array.from(value.entries()) };
203
- } else if (value instanceof Set) {
204
- value = { [CACHING_TYPE]: "Set", [CACHING_DATA]: Array.from(value.values()) };
205
- } else if (typeof value === "bigint") {
206
- value = { [CACHING_TYPE]: "BigInt", [CACHING_DATA]: value.toString() };
207
- } else if (value && typeof value === "object") {
208
- if (Array.isArray(value)) {
209
- value = value.map((v) => this.convertDate(v));
210
- } else {
211
- value = Object.fromEntries(
212
- Object.entries(value).map(([k, v]) => {
213
- return [k, this.convertDate(v)];
214
- })
215
- );
216
- }
217
- }
218
- return value;
219
- }
220
- convertDate(value) {
221
- if (value instanceof Date) {
222
- return { [CACHING_TYPE]: "Date", [CACHING_DATA]: value.toISOString() };
223
- }
224
- return value;
225
- }
226
- decodeValue(value, defaultValue) {
227
- if (value === null) {
228
- return defaultValue === void 0 ? null : defaultValue;
229
- }
230
- try {
231
- return JSON.parse(value, (_, v) => this.jsonParseReviver(v));
232
- } catch {
233
- return null;
234
- }
235
- }
236
- jsonParseReviver(value) {
237
- if (value && typeof value === "object") {
238
- const keys = Object.keys(value);
239
- if (keys.length === 2 && keys.includes(CACHING_TYPE) && keys.includes(CACHING_DATA)) {
240
- switch (value[CACHING_TYPE]) {
241
- case "Map":
242
- if (Array.isArray(value[CACHING_DATA])) {
243
- return new Map(value[CACHING_DATA]);
244
- }
245
- break;
246
- case "Set":
247
- if (Array.isArray(value[CACHING_DATA])) {
248
- return new Set(value[CACHING_DATA]);
249
- }
250
- break;
251
- case "Date":
252
- if (typeof value[CACHING_DATA] === "string") {
253
- return new Date(value[CACHING_DATA]);
254
- }
255
- break;
256
- case "BigInt":
257
- if (typeof value[CACHING_DATA] === "string") {
258
- return BigInt(value[CACHING_DATA]);
259
- }
260
- break;
261
- }
262
- }
263
- }
264
- return value;
265
- }
266
- };
267
-
268
- // src/i18n/index.ts
269
- import { I18n as I18n3 } from "@aomex/common";
270
-
271
- // src/i18n/locales/zh-cn.ts
272
- import { I18n } from "@aomex/common";
273
- var zh = I18n.define({
274
- wrong_type: "\u9519\u8BEF\u7684\u503C\u7C7B\u578B",
275
- not_integer: "\u503C\u4E0D\u662F\u6574\u6570\u7C7B\u578B"
276
- });
277
-
278
- // src/i18n/locales/en-us.ts
279
- import { I18n as I18n2 } from "@aomex/common";
280
- var en = I18n2.satisfies(zh).define({
281
- wrong_type: "wrong kind of value",
282
- not_integer: "value is not an integer"
283
- });
284
-
285
- // src/i18n/locales/index.ts
286
- var locales = {
287
- zh_CN: zh,
288
- en_US: en
9
+ adapter;
10
+ constructor(adapter) {
11
+ this.adapter = adapter;
12
+ }
13
+ /**
14
+ * 查看缓存是否存在
15
+ */
16
+ async exists(key) {
17
+ await this.adapter.connect();
18
+ return this.adapter.existsKey(key);
19
+ }
20
+ async get(key, defaultValue) {
21
+ await this.adapter.connect();
22
+ const result = await this.adapter.getValue(key);
23
+ return this.decodeValue(result, defaultValue);
24
+ }
25
+ /**
26
+ * 设置缓存。可以指定过期时间(毫秒)
27
+ *
28
+ * ```typescript
29
+ * await cache.set('key', 'value');
30
+ * await cache.set('key', 'value', 3600);
31
+ * ```
32
+ */
33
+ async set(key, value, durationMs) {
34
+ await this.adapter.connect();
35
+ return this.adapter.setValue(key, this.encodeValue(value), durationMs);
36
+ }
37
+ /**
38
+ * 设置缓存。如果缓存已经存在,则设置失败,返回`false`
39
+ *
40
+ * ```typescript
41
+ * await cache.setNX('foo', 'bar'); // true
42
+ * await cache.setNX('foo', 'baz'); // false
43
+ * ```
44
+ */
45
+ async setNX(key, value, durationMs) {
46
+ await this.adapter.connect();
47
+ return this.adapter.setNotExistValue(key, this.encodeValue(value), durationMs);
48
+ }
49
+ /**
50
+ * 将一个或多个值按顺序插入到列表头部。当 key 存在但不是列表类型时,返回一个错误。
51
+ *
52
+ * ```typescript
53
+ * await cache.leftPush('foo', 'a'); // ['a']
54
+ * await cache.leftPush('foo', 'b', 'c'); // ['b', 'c', 'a']
55
+ * ```
56
+ */
57
+ async leftPush(key, ...values) {
58
+ if (!values.length) return false;
59
+ await this.adapter.connect();
60
+ return this.adapter.leftPushValue(key, ...values.map((value) => this.encodeValue(value)));
61
+ }
62
+ /**
63
+ * 移除列表的最后一个元素,返回值为被移除的元素
64
+ */
65
+ async rightPop(key) {
66
+ await this.adapter.connect();
67
+ const result = await this.adapter.rightPopValue(key);
68
+ return this.decodeValue(result);
69
+ }
70
+ /**
71
+ * 将key中储存的数字值增一。如果key不存在,那么key的值会先被初始化为0,然后再执行操作。如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。
72
+ *
73
+ * ```typescript
74
+ * await cache.increment('foo'); // 1
75
+ * await cache.increment('foo'); // 2
76
+ * await cache.increment('foo'); // 3
77
+ * ```
78
+ */
79
+ async increment(key) {
80
+ await this.adapter.connect();
81
+ return this.adapter.increaseValue(key);
82
+ }
83
+ /**
84
+ * 重新设置缓存时间。如果key不存在,则返回`false`
85
+ */
86
+ async expire(key, durationMs) {
87
+ await this.adapter.connect();
88
+ return this.adapter.expireKey(key, durationMs);
89
+ }
90
+ /**
91
+ * 检测缓存的剩余生存时间(Time to live)
92
+ * - 不存在则返回`-2`
93
+ * - 未设置过期时间则返回`-1`
94
+ * - 已设置过期时间则返回剩余时间,单位**毫秒**
95
+ *
96
+ * ```typescript
97
+ * await cache.ttl('foo'); // -2
98
+ * await cache.set('foo', 'bar');
99
+ * await cache.ttl('foo'); // -1
100
+ * await cache.expire('foo', 60000);
101
+ * await cache.ttl('foo'); // 59000
102
+ * ```
103
+ */
104
+ async ttl(key) {
105
+ await this.adapter.connect();
106
+ return this.adapter.ttlKey(key);
107
+ }
108
+ /**
109
+ * 将key中储存的数字值减一。如果key不存在,那么key的值会先被初始化为0,然后再执行操作。如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误
110
+ */
111
+ async decrement(key) {
112
+ await this.adapter.connect();
113
+ return this.adapter.decreaseValue(key);
114
+ }
115
+ /**
116
+ * 删除指定缓存
117
+ */
118
+ async delete(key) {
119
+ await this.adapter.connect();
120
+ return this.adapter.deleteValue(key);
121
+ }
122
+ /**
123
+ * 删除所有缓存
124
+ */
125
+ async deleteAll() {
126
+ await this.adapter.connect();
127
+ return this.adapter.deleteAllValues();
128
+ }
129
+ encodeValue(value) {
130
+ if (value instanceof Date) value = this.convertDate(value);
131
+ return JSON.stringify(value, (_, v) => this.stringifyReplacer(v));
132
+ }
133
+ stringifyReplacer(value) {
134
+ if (value instanceof Map) value = {
135
+ [CACHING_TYPE]: "Map",
136
+ [CACHING_DATA]: Array.from(value.entries())
137
+ };
138
+ else if (value instanceof Set) value = {
139
+ [CACHING_TYPE]: "Set",
140
+ [CACHING_DATA]: Array.from(value.values())
141
+ };
142
+ else if (typeof value === "bigint") value = {
143
+ [CACHING_TYPE]: "BigInt",
144
+ [CACHING_DATA]: value.toString()
145
+ };
146
+ else if (value && typeof value === "object") {
147
+ if (Array.isArray(value)) value = value.map((v) => this.convertDate(v));
148
+ else value = Object.fromEntries(Object.entries(value).map(([k, v]) => {
149
+ return [k, this.convertDate(v)];
150
+ }));
151
+ }
152
+ return value;
153
+ }
154
+ convertDate(value) {
155
+ if (value instanceof Date) return {
156
+ [CACHING_TYPE]: "Date",
157
+ [CACHING_DATA]: value.toISOString()
158
+ };
159
+ return value;
160
+ }
161
+ decodeValue(value, defaultValue) {
162
+ if (value === null) return defaultValue === void 0 ? null : defaultValue;
163
+ try {
164
+ return JSON.parse(value, (_, v) => this.jsonParseReviver(v));
165
+ } catch {
166
+ return null;
167
+ }
168
+ }
169
+ jsonParseReviver(value) {
170
+ if (value && typeof value === "object") {
171
+ const keys = Object.keys(value);
172
+ if (keys.length === 2 && keys.includes(CACHING_TYPE) && keys.includes(CACHING_DATA)) switch (value[CACHING_TYPE]) {
173
+ case "Map":
174
+ if (Array.isArray(value[CACHING_DATA])) return new Map(value[CACHING_DATA]);
175
+ break;
176
+ case "Set":
177
+ if (Array.isArray(value[CACHING_DATA])) return new Set(value[CACHING_DATA]);
178
+ break;
179
+ case "Date":
180
+ if (typeof value[CACHING_DATA] === "string") return new Date(value[CACHING_DATA]);
181
+ break;
182
+ case "BigInt": if (typeof value[CACHING_DATA] === "string") return BigInt(value[CACHING_DATA]);
183
+ }
184
+ }
185
+ return value;
186
+ }
289
187
  };
290
-
291
- // src/i18n/index.ts
292
- var i18n = new I18n3({
293
- resources: locales,
294
- defaultLanguage: "zh_CN"
295
- });
296
-
297
- // src/cache-memory-adapter.ts
298
- var CacheMemoryAdapter = class extends CacheAdapter {
299
- data = /* @__PURE__ */ new Map();
300
- async existsKey(key) {
301
- return this.getValueSync(key, "any") !== null;
302
- }
303
- async getValue(key) {
304
- const value = this.getValueSync(key, "string");
305
- return value;
306
- }
307
- async setValue(key, value, duration) {
308
- return this.setValueSync(key, value, duration);
309
- }
310
- async setNotExistValue(key, value, duration) {
311
- const currentValue = this.getValueSync(key, "string");
312
- if (currentValue !== null) return false;
313
- return this.setValueSync(key, value, duration);
314
- }
315
- async leftPushValue(key, ...values) {
316
- let result = this.getValueSync(key, "array");
317
- if (result === null) result = [];
318
- result.push(...values);
319
- this.setValueSync(key, result);
320
- return true;
321
- }
322
- async rightPopValue(key) {
323
- let result = this.getValueSync(key, "array");
324
- if (result === null || !result.length) return null;
325
- const popValue = result.pop();
326
- if (result.length) {
327
- this.setValueSync(key, result);
328
- } else {
329
- this.data.delete(key);
330
- }
331
- return popValue;
332
- }
333
- async increaseValue(key) {
334
- const result = this.getValueSync(key, "string");
335
- let value;
336
- if (result === null) {
337
- this.data.set(key, { value: "0" });
338
- value = 0;
339
- } else {
340
- value = Number(result);
341
- }
342
- if (Number.isNaN(value) || !Number.isInteger(value)) {
343
- throw new Error("\u7F13\u5B58\u503C\u4E0D\u662F\u6574\u6570\u7C7B\u578B");
344
- }
345
- this.setValueSync(key, String(++value));
346
- return value;
347
- }
348
- async decreaseValue(key) {
349
- const result = this.getValueSync(key, "string");
350
- let value;
351
- if (result === null) {
352
- this.data.set(key, { value: "0" });
353
- value = 0;
354
- } else {
355
- value = Number(result);
356
- }
357
- if (Number.isNaN(value) || !Number.isInteger(value)) {
358
- throw new Error(i18n.t("not_integer"));
359
- }
360
- this.setValueSync(key, String(--value));
361
- return value;
362
- }
363
- async deleteValue(key) {
364
- this.data.delete(key);
365
- return true;
366
- }
367
- async deleteAllValues() {
368
- this.data.clear();
369
- return true;
370
- }
371
- async expireKey(key, duration) {
372
- const result = this.data.get(key);
373
- if (!result) return false;
374
- if (result.expires && result.expires < Date.now()) return false;
375
- result.expires = Date.now() + duration;
376
- return true;
377
- }
378
- async ttlKey(key) {
379
- const result = this.data.get(key);
380
- if (!result) return -2;
381
- if (!result.expires) return -1;
382
- if (result.expires < Date.now()) return -2;
383
- return result.expires - Date.now();
384
- }
385
- getValueSync(key, assertType) {
386
- const result = this.data.get(key);
387
- if (!result) return null;
388
- if (result.expires && result.expires < Date.now()) return null;
389
- const value = result.value;
390
- let isValid = false;
391
- switch (assertType) {
392
- case "string":
393
- isValid = typeof value === "string";
394
- break;
395
- case "array":
396
- isValid = Array.isArray(value);
397
- break;
398
- case "any":
399
- isValid = true;
400
- break;
401
- }
402
- if (!isValid) {
403
- throw new Error(i18n.t("wrong_type"));
404
- }
405
- return value;
406
- }
407
- setValueSync(key, value, duration) {
408
- this.data.set(key, { value, expires: duration ? Date.now() + duration : void 0 });
409
- return true;
410
- }
188
+ // src/remember.ts
189
+ function createRemember() {
190
+ let service;
191
+ const remember = ((optsOrDurationMs) => {
192
+ const { key: getKey, duration, defaultValue = null } = typeof optsOrDurationMs === "number" ? { duration: optsOrDurationMs } : optsOrDurationMs;
193
+ return (originalMethod, context) => {
194
+ return async function(...args) {
195
+ if (!service) throw new Error("Cache service is not registered; call remember.setInstance(service) first");
196
+ const cache = service["_cache"];
197
+ const dataKey = getKey === void 0 ? `${"displayName" in this && typeof this.displayName === "string" ? this.displayName : this.constructor.name}-${String(context.name)}-${JSON.stringify(args)}` : typeof getKey === "string" ? getKey : getKey.apply(this, args);
198
+ const waitingKey = dataKey + ":$#_waiting_#$";
199
+ const value = await traceBlock("Cache.get", () => cache.get(dataKey));
200
+ if (value !== null) return value;
201
+ if (await cache.setNX(waitingKey, 1, 2e4)) {
202
+ const timer = setInterval(() => {
203
+ cache.expire(waitingKey, 2e4);
204
+ }, 5e3);
205
+ try {
206
+ const result = await traceBlock("Cache.exec", async () => {
207
+ return originalMethod.apply(this, args);
208
+ });
209
+ if (result !== null) await traceBlock("Cache.set", async () => {
210
+ await cache.set(dataKey, result, duration);
211
+ });
212
+ return result === null ? defaultValue : result;
213
+ } finally {
214
+ clearInterval(timer);
215
+ await cache.delete(waitingKey);
216
+ }
217
+ } else return traceBlock("Cache.wait", async () => {
218
+ while (true) {
219
+ if (await cache.exists(waitingKey)) {
220
+ await sleep(100);
221
+ continue;
222
+ }
223
+ return cache.get(dataKey, defaultValue);
224
+ }
225
+ });
226
+ };
227
+ };
228
+ });
229
+ remember.setInstance = (next) => {
230
+ if (service !== void 0 && service !== next) throw new Error("Only one cache service is allowed");
231
+ service = next;
232
+ };
233
+ remember.deleteInstance = () => {
234
+ service = void 0;
235
+ };
236
+ remember.fork = () => createRemember();
237
+ return remember;
238
+ }
239
+ /**
240
+ * 方法装饰器:自动获取缓存,未命中则执行原方法并写入;并发相同 key 会截流共享首个请求。
241
+ * 每个 remember(含 `fork()` 产物)各自只允许登记一个 `BaseCacheService`。
242
+ *
243
+ * ```typescript
244
+ * class CacheService extends BaseCacheService {
245
+ * protected createAdapter() {
246
+ * return new CacheRedisAdapter({ host: '127.0.0.1' });
247
+ * }
248
+ *
249
+ * protected override async onInit() {
250
+ * await super.onInit();
251
+ * remember.setInstance(this);
252
+ * }
253
+ *
254
+ * protected override async onDestroy() {
255
+ * remember.deleteInstance();
256
+ * await super.onDestroy();
257
+ * }
258
+ * }
259
+ *
260
+ * await combineServices(
261
+ * {
262
+ * cache: () => import('./cache.service.js'),
263
+ * report: () => import('./report.service.js'),
264
+ * },
265
+ * { eager: ['cache'] },
266
+ * );
267
+ *
268
+ * class Report {
269
+ * @remember(60_000)
270
+ * async build() {
271
+ * return { ok: true };
272
+ * }
273
+ * }
274
+ *
275
+ * // 另一套缓存作用域
276
+ * const rememberB = remember.fork();
277
+ * rememberB.setInstance(otherCacheService);
278
+ * ```
279
+ */
280
+ const remember = createRemember();
281
+ // src/base-cache-service.ts
282
+ const CACHE_TTL = {
283
+ SECOND: 1e3,
284
+ MINUTE: 6e4,
285
+ HOUR: 36e5,
286
+ DAY: 864e5,
287
+ WEEK: 6048e5,
288
+ /** 按 30 天计 */
289
+ MONTH: 2592e6,
290
+ /** 按 365 天计 */
291
+ YEAR: 31536e6
411
292
  };
412
- var memoryAdapter = () => new CacheMemoryAdapter();
413
- export {
414
- CacheAdapter,
415
- CacheMemoryAdapter,
416
- Caching,
417
- memoryAdapter
293
+ /**
294
+ * 缓存领域服务基类:子类实现 `createAdapter`,在业务方法里通过 `this.cache` 访问。
295
+ *
296
+ * ```typescript
297
+ * import { CacheMemoryAdapter } from '@aomex/cache/memory';
298
+ *
299
+ * class CacheService extends BaseCacheService {
300
+ * protected createAdapter() {
301
+ * return new CacheMemoryAdapter();
302
+ * }
303
+ * }
304
+ * ```
305
+ */
306
+ var BaseCacheService = class extends Service {
307
+ _cache;
308
+ get cache() {
309
+ return this._cache;
310
+ }
311
+ async onInit() {
312
+ this._cache = new Caching(this.createAdapter());
313
+ await this._cache.adapter.connect();
314
+ }
315
+ async onDestroy() {
316
+ await this._cache?.adapter.disconnect();
317
+ }
318
+ /** 常用过期时间(毫秒):`this.ttl.DAY` */
319
+ get ttl() {
320
+ return CACHE_TTL;
321
+ }
322
+ /** 用 `:` 拼接缓存 key 片段,如 `concat('user', 1)` → `'user:1'` */
323
+ concat(...keys) {
324
+ return keys.join(":");
325
+ }
326
+ /** 对 key 做 MD5,适合过长或不规则片段 */
327
+ hash(key) {
328
+ return createHash("md5").update(String(key)).digest("hex");
329
+ }
418
330
  };
331
+ export { BaseCacheService, CacheAdapter, Caching, remember };
332
+
419
333
  //# sourceMappingURL=index.js.map