@aomex/cache 3.30.7 → 3.30.8-alpha.3d94097.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,397 @@
1
- // src/caching.ts
1
+ import { n as CacheAdapter, t as i18n } from "./i18n-OXOpRIod.js";
2
+ import { createHash } from "node:crypto";
2
3
  import { traceBlock } from "@aomex/async-trace";
3
-
4
- // src/cache-adapter.ts
5
- var CacheAdapter = class {
6
- async connect() {
7
- }
4
+ import { Service, sleep } from "@aomex/common";
5
+ // src/cache-key.ts
6
+ /**
7
+ * 缓存键。通常由 `BaseCacheService#key()` / `#keyHash()` 创建。
8
+ *
9
+ * ```typescript
10
+ * this.key('user', 1); // user:1
11
+ * this.key('user').key(1); // user:1
12
+ * this.keyHash('user', 1); // md5('user:1')
13
+ * this.key('user').keyHash(1); // user:md5('1')
14
+ * this.key('user', 1).toHash(); // md5('user:1')
15
+ * await this.cache.get(this.key('user', 1));
16
+ * ```
17
+ */
18
+ var CacheKey = class CacheKey {
19
+ value;
20
+ constructor(value = "") {
21
+ this.value = value;
22
+ }
23
+ /** 用 `:` 拼接片段(保留已有前缀),如 `key('user').key(1)` → `'user:1'` */
24
+ key(...keys) {
25
+ return new CacheKey((this.value === "" ? keys : [this.value, ...keys]).join(":"));
26
+ }
27
+ /** 仅对本次参数拼接后 MD5,再接到已有前缀后 */
28
+ keyHash(...keys) {
29
+ return this.key(this.md5(keys.join(":")));
30
+ }
31
+ /** 对当前完整键做 MD5 */
32
+ toHash() {
33
+ return new CacheKey(this.md5(this.value));
34
+ }
35
+ toString() {
36
+ return this.value;
37
+ }
38
+ md5(key) {
39
+ return createHash("md5").update(String(key)).digest("hex");
40
+ }
8
41
  };
9
-
10
42
  // src/caching.ts
11
- import { sleep } from "@aomex/common";
12
- var CACHING_TYPE = "_$caching_type$_";
13
- var CACHING_DATA = "_$caching_data$_";
43
+ const CACHING_TYPE = "_$caching_type$_";
44
+ const CACHING_DATA = "_$caching_data$_";
14
45
  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
- }
46
+ adapter;
47
+ constructor(adapter) {
48
+ this.adapter = adapter;
49
+ }
50
+ /**
51
+ * 查看缓存是否存在
52
+ */
53
+ async exists(key) {
54
+ await this.adapter.connect();
55
+ return this.adapter.existsKey(this.resolveKey(key));
56
+ }
57
+ async get(key, defaultValue) {
58
+ await this.adapter.connect();
59
+ const result = await this.adapter.getValue(this.resolveKey(key));
60
+ return this.decodeValue(result, defaultValue);
61
+ }
62
+ /**
63
+ * 设置缓存。可以指定过期时间(毫秒)
64
+ *
65
+ * ```typescript
66
+ * await cache.set('key', 'value');
67
+ * await cache.set('key', 'value', 3600);
68
+ * ```
69
+ */
70
+ async set(key, value, durationMs) {
71
+ await this.adapter.connect();
72
+ return this.adapter.setValue(this.resolveKey(key), this.encodeValue(value), durationMs);
73
+ }
74
+ /**
75
+ * 设置缓存。如果缓存已经存在,则设置失败,返回`false`
76
+ *
77
+ * ```typescript
78
+ * await cache.setNX('foo', 'bar'); // true
79
+ * await cache.setNX('foo', 'baz'); // false
80
+ * ```
81
+ */
82
+ async setNX(key, value, durationMs) {
83
+ await this.adapter.connect();
84
+ return this.adapter.setNotExistValue(this.resolveKey(key), this.encodeValue(value), durationMs);
85
+ }
86
+ /**
87
+ * 将一个或多个值按顺序插入到列表头部。当 key 存在但不是列表类型时,返回一个错误。
88
+ *
89
+ * ```typescript
90
+ * await cache.leftPush('foo', 'a'); // ['a']
91
+ * await cache.leftPush('foo', 'b', 'c'); // ['b', 'c', 'a']
92
+ * ```
93
+ */
94
+ async leftPush(key, ...values) {
95
+ if (!values.length) return false;
96
+ await this.adapter.connect();
97
+ return this.adapter.leftPushValue(this.resolveKey(key), ...values.map((value) => this.encodeValue(value)));
98
+ }
99
+ /**
100
+ * 移除列表的最后一个元素,返回值为被移除的元素
101
+ */
102
+ async rightPop(key) {
103
+ await this.adapter.connect();
104
+ const result = await this.adapter.rightPopValue(this.resolveKey(key));
105
+ return this.decodeValue(result);
106
+ }
107
+ /**
108
+ * 将key中储存的数字值增一。如果key不存在,那么key的值会先被初始化为0,然后再执行操作。如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。
109
+ *
110
+ * ```typescript
111
+ * await cache.increment('foo'); // 1
112
+ * await cache.increment('foo'); // 2
113
+ * await cache.increment('foo'); // 3
114
+ * ```
115
+ */
116
+ async increment(key) {
117
+ await this.adapter.connect();
118
+ return this.adapter.increaseValue(this.resolveKey(key));
119
+ }
120
+ /**
121
+ * 重新设置缓存时间。如果key不存在,则返回`false`
122
+ */
123
+ async expire(key, durationMs) {
124
+ await this.adapter.connect();
125
+ return this.adapter.expireKey(this.resolveKey(key), durationMs);
126
+ }
127
+ /**
128
+ * 检测缓存的剩余生存时间(Time to live)
129
+ * - 不存在则返回`-2`
130
+ * - 未设置过期时间则返回`-1`
131
+ * - 已设置过期时间则返回剩余时间,单位**毫秒**
132
+ *
133
+ * ```typescript
134
+ * await cache.ttl('foo'); // -2
135
+ * await cache.set('foo', 'bar');
136
+ * await cache.ttl('foo'); // -1
137
+ * await cache.expire('foo', 60000);
138
+ * await cache.ttl('foo'); // 59000
139
+ * ```
140
+ */
141
+ async ttl(key) {
142
+ await this.adapter.connect();
143
+ return this.adapter.ttlKey(this.resolveKey(key));
144
+ }
145
+ /**
146
+ * 将key中储存的数字值减一。如果key不存在,那么key的值会先被初始化为0,然后再执行操作。如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误
147
+ */
148
+ async decrement(key) {
149
+ await this.adapter.connect();
150
+ return this.adapter.decreaseValue(this.resolveKey(key));
151
+ }
152
+ /**
153
+ * 删除指定缓存
154
+ */
155
+ async delete(key) {
156
+ await this.adapter.connect();
157
+ return this.adapter.deleteValue(this.resolveKey(key));
158
+ }
159
+ /**
160
+ * 删除所有缓存
161
+ */
162
+ async deleteAll() {
163
+ await this.adapter.connect();
164
+ return this.adapter.deleteAllValues();
165
+ }
166
+ resolveKey(key) {
167
+ return typeof key === "string" ? key : key["value"];
168
+ }
169
+ encodeValue(value) {
170
+ if (value instanceof Date) value = this.convertDate(value);
171
+ return JSON.stringify(value, (_, v) => this.stringifyReplacer(v));
172
+ }
173
+ stringifyReplacer(value) {
174
+ if (value instanceof Map) value = {
175
+ [CACHING_TYPE]: "Map",
176
+ [CACHING_DATA]: Array.from(value.entries())
177
+ };
178
+ else if (value instanceof Set) value = {
179
+ [CACHING_TYPE]: "Set",
180
+ [CACHING_DATA]: Array.from(value.values())
181
+ };
182
+ else if (typeof value === "bigint") value = {
183
+ [CACHING_TYPE]: "BigInt",
184
+ [CACHING_DATA]: value.toString()
185
+ };
186
+ else if (value && typeof value === "object") {
187
+ if (Array.isArray(value)) value = value.map((v) => this.convertDate(v));
188
+ else value = Object.fromEntries(Object.entries(value).map(([k, v]) => {
189
+ return [k, this.convertDate(v)];
190
+ }));
191
+ }
192
+ return value;
193
+ }
194
+ convertDate(value) {
195
+ if (value instanceof Date) return {
196
+ [CACHING_TYPE]: "Date",
197
+ [CACHING_DATA]: value.toISOString()
198
+ };
199
+ return value;
200
+ }
201
+ decodeValue(value, defaultValue) {
202
+ if (value === null) return defaultValue === void 0 ? null : defaultValue;
203
+ try {
204
+ return JSON.parse(value, (_, v) => this.jsonParseReviver(v));
205
+ } catch {
206
+ return null;
207
+ }
208
+ }
209
+ jsonParseReviver(value) {
210
+ if (value && typeof value === "object") {
211
+ const keys = Object.keys(value);
212
+ if (keys.length === 2 && keys.includes(CACHING_TYPE) && keys.includes(CACHING_DATA)) switch (value[CACHING_TYPE]) {
213
+ case "Map":
214
+ if (Array.isArray(value[CACHING_DATA])) return new Map(value[CACHING_DATA]);
215
+ break;
216
+ case "Set":
217
+ if (Array.isArray(value[CACHING_DATA])) return new Set(value[CACHING_DATA]);
218
+ break;
219
+ case "Date":
220
+ if (typeof value[CACHING_DATA] === "string") return new Date(value[CACHING_DATA]);
221
+ break;
222
+ case "BigInt": if (typeof value[CACHING_DATA] === "string") return BigInt(value[CACHING_DATA]);
223
+ }
224
+ }
225
+ return value;
226
+ }
266
227
  };
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
228
+ // src/remember.ts
229
+ /** 每个服务类一份:当前 `Caching` + 未就绪时的等待 Promise */
230
+ const stateByCtor = /* @__PURE__ */ new WeakMap();
231
+ function getState(ctor) {
232
+ const existing = stateByCtor.get(ctor);
233
+ if (existing) return existing;
234
+ const state = {
235
+ cache: void 0,
236
+ destroyed: false,
237
+ ready: Promise.withResolvers()
238
+ };
239
+ stateByCtor.set(ctor, state);
240
+ return state;
241
+ }
242
+ async function ensureCache(ctor) {
243
+ const state = getState(ctor);
244
+ if (state.destroyed) throw new Error(i18n.t("cache_service_destroyed"));
245
+ if (state.cache) return state.cache;
246
+ await state.ready.promise;
247
+ if (state.destroyed || !state.cache) throw new Error(i18n.t("cache_service_destroyed"));
248
+ return state.cache;
249
+ }
250
+ /** 供 `BaseCacheService.onInit` 挂载;包外请勿直接调用 */
251
+ function attachRememberScopes(service) {
252
+ const ctor = service.constructor;
253
+ const cache = service["_cache"];
254
+ const state = getState(ctor);
255
+ state.destroyed = false;
256
+ state.cache = cache;
257
+ state.ready.resolve(cache);
258
+ }
259
+ /** 供 `BaseCacheService.onDestroy` / `onInit` 失败时卸载;包外请勿直接调用 */
260
+ function detachRememberScopes(service) {
261
+ const ctor = service.constructor;
262
+ const state = stateByCtor.get(ctor);
263
+ if (!state) return;
264
+ if (state.cache !== void 0 && state.cache !== service["_cache"]) return;
265
+ state.destroyed = true;
266
+ state.cache = void 0;
267
+ state.ready.reject(new Error(i18n.t("cache_service_destroyed")));
268
+ }
269
+ /**
270
+ * 创建绑定到指定 `BaseCacheService` 子类的 remember 装饰器。
271
+ * 必须传入具体子类,不能传入 `BaseCacheService` 本身。
272
+ *
273
+ * ```typescript
274
+ * export const remember = createRemember(CacheService);
275
+ * ```
276
+ */
277
+ function createRemember(ctor) {
278
+ const remember = ((optsOrDurationMs) => {
279
+ const { key: getKey, duration, defaultValue = null } = typeof optsOrDurationMs === "number" ? { duration: optsOrDurationMs } : optsOrDurationMs;
280
+ return (originalMethod, context) => {
281
+ return async function(...args) {
282
+ const cache = await ensureCache(ctor);
283
+ 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);
284
+ const waitingKey = dataKey + ":$#_waiting_#$";
285
+ const value = await traceBlock("Cache.get", () => cache.get(dataKey));
286
+ if (value !== null) return value;
287
+ if (await cache.setNX(waitingKey, 1, 2e4)) {
288
+ const timer = setInterval(() => {
289
+ cache.expire(waitingKey, 2e4);
290
+ }, 5e3);
291
+ try {
292
+ const result = await traceBlock("Cache.exec", async () => {
293
+ return originalMethod.apply(this, args);
294
+ });
295
+ if (result !== null) await traceBlock("Cache.set", async () => {
296
+ await cache.set(dataKey, result, duration);
297
+ });
298
+ return result === null ? defaultValue : result;
299
+ } finally {
300
+ clearInterval(timer);
301
+ await cache.delete(waitingKey);
302
+ }
303
+ } else return traceBlock("Cache.wait", async () => {
304
+ while (true) {
305
+ if (await cache.exists(waitingKey)) {
306
+ await sleep(100);
307
+ continue;
308
+ }
309
+ return cache.get(dataKey, defaultValue);
310
+ }
311
+ });
312
+ };
313
+ };
314
+ });
315
+ return remember;
316
+ }
317
+ // src/base-cache-service.ts
318
+ const CACHE_TTL = {
319
+ SECOND: 1e3,
320
+ MINUTE: 6e4,
321
+ HOUR: 36e5,
322
+ DAY: 864e5,
323
+ WEEK: 6048e5,
324
+ /** 按 30 天计 */
325
+ MONTH: 2592e6,
326
+ /** 按 365 天计 */
327
+ YEAR: 31536e6
289
328
  };
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
- }
411
- };
412
- var memoryAdapter = () => new CacheMemoryAdapter();
413
- export {
414
- CacheAdapter,
415
- CacheMemoryAdapter,
416
- Caching,
417
- memoryAdapter
329
+ /**
330
+ * 缓存领域服务基类:子类实现 `createAdapter`,在业务方法里通过 `this.cache` 访问。
331
+ *
332
+ * ```typescript
333
+ * import { CacheMemoryAdapter } from '@aomex/cache/memory';
334
+ * import { createRemember } from '@aomex/cache';
335
+ *
336
+ * class CacheService extends BaseCacheService {
337
+ * protected createAdapter() {
338
+ * return new CacheMemoryAdapter();
339
+ * }
340
+ * }
341
+ *
342
+ * export const remember = createRemember(CacheService);
343
+ * ```
344
+ */
345
+ var BaseCacheService = class extends Service {
346
+ _cache;
347
+ get cache() {
348
+ return this._cache;
349
+ }
350
+ async onInit() {
351
+ this._cache = new Caching(this.createAdapter());
352
+ try {
353
+ await this._cache.adapter.connect();
354
+ attachRememberScopes(this);
355
+ } catch (e) {
356
+ detachRememberScopes(this);
357
+ throw e;
358
+ }
359
+ }
360
+ async onDestroy() {
361
+ detachRememberScopes(this);
362
+ await this._cache?.adapter.disconnect();
363
+ }
364
+ /** 常用过期时间(毫秒):`this.ttl.DAY` */
365
+ get ttl() {
366
+ return CACHE_TTL;
367
+ }
368
+ /**
369
+ * 用 `:` 拼接片段,得到可读的缓存键(可继续链式调用)。
370
+ *
371
+ * ```typescript
372
+ * this.key('user', 1); // user:1
373
+ * this.key('user').key(1); // 同上
374
+ * this.key('user').keyHash(1); // user:<md5('1')> 前缀保留,只哈希新片段
375
+ * this.key('user', 1).toHash(); // <md5('user:1')> 整键再哈希
376
+ * await this.cache.get(this.key('user', 1));
377
+ * ```
378
+ */
379
+ key(...keys) {
380
+ return keys.length === 0 ? new CacheKey() : new CacheKey().key(...keys);
381
+ }
382
+ /**
383
+ * 将片段用 `:` 拼接后整体 MD5(无可读前缀)。
384
+ * 等价于 `this.key(...keys).toHash()`。
385
+ *
386
+ * ```typescript
387
+ * this.keyHash('user', 1); // <md5('user:1')>
388
+ * this.key('user').keyHash(1); // 不是这个:那是「前缀 + 哈希段」
389
+ * ```
390
+ */
391
+ keyHash(...keys) {
392
+ return new CacheKey().keyHash(...keys);
393
+ }
418
394
  };
395
+ export { BaseCacheService, CacheAdapter, CacheKey, Caching, createRemember };
396
+
419
397
  //# sourceMappingURL=index.js.map