@zenweb/cache 4.7.1 → 5.0.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/cache.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- /// <reference types="node" />
2
1
  import { Redis, RedisValue } from 'ioredis';
3
- import { SetupOption, SetOption, GetOption, LockGetOption, SetResult, LockOption } from './types';
2
+ import { SetupOption, SetOption, GetOption, LockGetOption, SetResult, LockOption } from './types.js';
4
3
  /**
5
4
  * 缓存结果
6
5
  */
package/dist/cache.js CHANGED
@@ -1,20 +1,19 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Cache = exports.CacheResult = void 0;
4
- const zlib_1 = require("zlib");
5
- const util_1 = require("util");
6
- const locker_1 = require("./locker");
7
- const utils_1 = require("./utils");
8
- const compress = (0, util_1.promisify)(zlib_1.gzip);
9
- const decompress = (0, util_1.promisify)(zlib_1.unzip);
1
+ import { gzip, unzip } from 'node:zlib';
2
+ import { promisify } from 'node:util';
3
+ import { Locker } from './locker.js';
4
+ import { debug, sleep } from './utils.js';
5
+ const compress = promisify(gzip);
6
+ const decompress = promisify(unzip);
10
7
  const GZ_HEADER = Buffer.from([0x1F, 0x8B, 0x08]);
11
- const _getDebug = utils_1.debug.extend('get');
12
- const _setDebug = utils_1.debug.extend('set');
13
- const _lockDebug = utils_1.debug.extend('lock');
8
+ const _getDebug = debug.extend('get');
9
+ const _setDebug = debug.extend('set');
10
+ const _lockDebug = debug.extend('lock');
14
11
  /**
15
12
  * 缓存结果
16
13
  */
17
- class CacheResult {
14
+ export class CacheResult {
15
+ compressed;
16
+ data;
18
17
  /**
19
18
  * @param compressed 是否为压缩数据
20
19
  * @param data 数据
@@ -24,11 +23,12 @@ class CacheResult {
24
23
  this.data = data;
25
24
  }
26
25
  }
27
- exports.CacheResult = CacheResult;
28
26
  /**
29
27
  * 对象缓存系统
30
28
  */
31
- class Cache {
29
+ export class Cache {
30
+ redis;
31
+ option;
32
32
  constructor(redis, option) {
33
33
  this.redis = redis;
34
34
  this.option = option;
@@ -123,7 +123,7 @@ class Cache {
123
123
  */
124
124
  async singleRunner(key, run, _opt) {
125
125
  const opt = Object.assign({}, this.option.lockGet, _opt);
126
- const locker = new locker_1.Locker(this.redis, key, opt.lockTimeout);
126
+ const locker = new Locker(this.redis, key, opt.lockTimeout);
127
127
  const retryTimeout = typeof opt.retryTimeout === 'number' ? opt.retryTimeout : 0;
128
128
  const retryDelay = (opt.retryDelay === undefined || opt.retryDelay < 0) ? 500 : opt.retryDelay;
129
129
  let retryTime = 0;
@@ -143,13 +143,17 @@ class Cache {
143
143
  }
144
144
  else {
145
145
  retryTime += retryDelay;
146
- await (0, utils_1.sleep)(retryDelay);
146
+ await sleep(retryDelay);
147
147
  }
148
148
  }
149
149
  }
150
150
  }
151
- exports.Cache = Cache;
152
151
  class LockGet {
152
+ cache;
153
+ key;
154
+ fetch;
155
+ opt;
156
+ locker;
153
157
  constructor(cache, key, fetch, opt) {
154
158
  this.cache = cache;
155
159
  this.key = key;
@@ -209,7 +213,7 @@ class LockGet {
209
213
  let retryTime = 0;
210
214
  while (true) {
211
215
  if (!this.locker) {
212
- this.locker = new locker_1.Locker(this.cache.redis, `${this.key}.LOCK`, this.opt.lockTimeout);
216
+ this.locker = new Locker(this.cache.redis, `${this.key}.LOCK`, this.opt.lockTimeout);
213
217
  }
214
218
  else {
215
219
  // 尝试从 redis 中获取
@@ -240,7 +244,7 @@ class LockGet {
240
244
  }
241
245
  else {
242
246
  retryTime += retryDelay;
243
- await (0, utils_1.sleep)(retryDelay);
247
+ await sleep(retryDelay);
244
248
  }
245
249
  }
246
250
  }
package/dist/global.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * 取得缓存实例
3
3
  */
4
- export declare function getCache(): import("./cache").Cache;
4
+ export declare function $getCache(): import("./cache.js").Cache;
5
5
  /**
6
6
  * 快捷方法 - 缓存实例
7
7
  */
8
- export declare const $cache: import("./cache").Cache;
8
+ export declare const $cache: import("./cache.js").Cache;
package/dist/global.js CHANGED
@@ -1,16 +1,12 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.$cache = exports.getCache = void 0;
4
- const core_1 = require("@zenweb/core");
1
+ import { callProxy, $getCore } from "@zenweb/core";
5
2
  /**
6
3
  * 取得缓存实例
7
4
  */
8
- function getCache() {
9
- const ins = (0, core_1.getCore)();
5
+ export function $getCache() {
6
+ const ins = $getCore();
10
7
  return ins.cache2;
11
8
  }
12
- exports.getCache = getCache;
13
9
  /**
14
10
  * 快捷方法 - 缓存实例
15
11
  */
16
- exports.$cache = (0, core_1.callProxy)(getCache);
12
+ export const $cache = callProxy($getCache);
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { SetupFunction } from '@zenweb/core';
2
- import { SetupOption } from './types';
3
- import { Cache } from './cache';
2
+ import { SetupOption } from './types.js';
3
+ import { Cache } from './cache.js';
4
4
  import { Redis } from 'ioredis';
5
- export { getCache, $cache } from './global';
6
- export * from './types';
7
- export * from './utils';
8
- export { Locker } from './locker';
9
- export { cached } from './middleware';
5
+ export { $getCache, $cache } from './global.js';
6
+ export * from './types.js';
7
+ export * from './utils.js';
8
+ export { Locker } from './locker.js';
9
+ export { cached } from './middleware.js';
10
10
  export { Cache };
11
11
  /**
12
12
  * 安装模块
package/dist/index.js CHANGED
@@ -1,50 +1,28 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.Cache = exports.cached = exports.Locker = exports.$cache = exports.getCache = void 0;
18
- const cache_1 = require("./cache");
19
- Object.defineProperty(exports, "Cache", { enumerable: true, get: function () { return cache_1.Cache; } });
20
- const ioredis_1 = require("ioredis");
21
- const options_1 = require("./options");
22
- var global_1 = require("./global");
23
- Object.defineProperty(exports, "getCache", { enumerable: true, get: function () { return global_1.getCache; } });
24
- Object.defineProperty(exports, "$cache", { enumerable: true, get: function () { return global_1.$cache; } });
25
- __exportStar(require("./types"), exports);
26
- __exportStar(require("./utils"), exports);
27
- var locker_1 = require("./locker");
28
- Object.defineProperty(exports, "Locker", { enumerable: true, get: function () { return locker_1.Locker; } });
29
- var middleware_1 = require("./middleware");
30
- Object.defineProperty(exports, "cached", { enumerable: true, get: function () { return middleware_1.cached; } });
1
+ import { Cache } from './cache.js';
2
+ import { Redis } from 'ioredis';
3
+ import { defaultSetupOption } from './options.js';
4
+ export { $getCache, $cache } from './global.js';
5
+ export * from './types.js';
6
+ export * from './utils.js';
7
+ export { Locker } from './locker.js';
8
+ export { cached } from './middleware.js';
9
+ export { Cache };
31
10
  /**
32
11
  * 安装模块
33
12
  * @param option 配置
34
13
  */
35
- function setup(option) {
14
+ export default function setup(option) {
36
15
  return async function cache(setup) {
37
16
  setup.assertModuleExists('result', 'need setup @zenweb/result');
38
- const opt = Object.assign({}, options_1.defaultSetupOption, option);
17
+ const opt = Object.assign({}, defaultSetupOption, option);
39
18
  setup.debug('option: %o', opt);
40
- const redis = opt.redis instanceof ioredis_1.Redis ? opt.redis : new ioredis_1.Redis(opt.redis);
19
+ const redis = opt.redis instanceof Redis ? opt.redis : new Redis(opt.redis);
41
20
  await redis.ping('check');
42
21
  setup.defineCoreProperty('redis2', { value: redis });
43
- setup.defineCoreProperty('cache2', { value: new cache_1.Cache(redis, opt) });
22
+ setup.defineCoreProperty('cache2', { value: new Cache(redis, opt) });
44
23
  setup.destroy(async () => {
45
24
  setup.debug('quit redis...');
46
25
  await redis.quit();
47
26
  });
48
27
  };
49
28
  }
50
- exports.default = setup;
package/dist/locker.js CHANGED
@@ -1,8 +1,5 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Locker = void 0;
4
- const crypto_1 = require("crypto");
5
- const utils_1 = require("./utils");
1
+ import { randomBytes, createHash } from 'node:crypto';
2
+ import { runRedisScript } from './utils.js';
6
3
  const RELEASE_SCRIPT = `
7
4
  if redis.call("get", KEYS[1]) == ARGV[1] then
8
5
  return redis.call("del", KEYS[1])
@@ -10,11 +7,15 @@ else
10
7
  return 0
11
8
  end
12
9
  `;
13
- const RELEASE_SCRIPT_HASH = (0, crypto_1.createHash)('sha1').update(RELEASE_SCRIPT).digest('hex');
10
+ const RELEASE_SCRIPT_HASH = createHash('sha1').update(RELEASE_SCRIPT).digest('hex');
14
11
  /**
15
12
  * 基于 Redis 的分布式锁
16
13
  */
17
- class Locker {
14
+ export class Locker {
15
+ redis;
16
+ key;
17
+ timeout;
18
+ value = randomBytes(16).toString('hex');
18
19
  /**
19
20
  * @param redis Redis 实例
20
21
  * @param key 锁KEY
@@ -24,7 +25,6 @@ class Locker {
24
25
  this.redis = redis;
25
26
  this.key = key;
26
27
  this.timeout = timeout;
27
- this.value = (0, crypto_1.randomBytes)(16).toString('hex');
28
28
  }
29
29
  /**
30
30
  * 取得锁
@@ -40,7 +40,7 @@ class Locker {
40
40
  * 释放锁
41
41
  */
42
42
  async release() {
43
- return (await (0, utils_1.runRedisScript)(this.redis, RELEASE_SCRIPT_HASH, RELEASE_SCRIPT, [this.key], [this.value])) === 1;
43
+ return (await runRedisScript(this.redis, RELEASE_SCRIPT_HASH, RELEASE_SCRIPT, [this.key], [this.value])) === 1;
44
44
  }
45
45
  /**
46
46
  * 使用锁回调
@@ -59,4 +59,3 @@ class Locker {
59
59
  callback(false);
60
60
  }
61
61
  }
62
- exports.Locker = Locker;
@@ -1,5 +1,5 @@
1
1
  import { Context, Middleware } from "@zenweb/core";
2
- import { LockGetOption } from "./types";
2
+ import { LockGetOption } from "./types.js";
3
3
  type CachedMiddlewareOption = Omit<LockGetOption, 'parse' | 'decompress'>;
4
4
  /**
5
5
  * 缓存中间件
@@ -1,13 +1,10 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.cached = void 0;
4
1
  /**
5
2
  * 缓存中间件
6
3
  * - 缓存 ctx.success() 结果
7
4
  * - fail() 时不缓存
8
5
  * @param key 不指定 `key` 则默认使用 `ctx.path`,`key: null` 不适用使用缓存
9
6
  */
10
- function cached(key, opt) {
7
+ export function cached(key, opt) {
11
8
  return async function cachedMiddleware(ctx, next) {
12
9
  const _key = typeof key === 'string' ? key
13
10
  : typeof key === 'function' ? await key(ctx)
@@ -23,4 +20,3 @@ function cached(key, opt) {
23
20
  ctx.success(result);
24
21
  };
25
22
  }
26
- exports.cached = cached;
package/dist/options.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { RedisOptions } from "ioredis";
2
- import type { LockGetOption, ObjectSerializer, SetOption, SetupOption } from "./types";
2
+ import type { LockGetOption, ObjectSerializer, SetOption, SetupOption } from "./types.js";
3
3
  export declare const defaultRedisOption: RedisOptions;
4
4
  export declare const defaultSetOption: SetOption;
5
5
  export declare const defaultLockGetOption: LockGetOption;
package/dist/options.js CHANGED
@@ -1,26 +1,23 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.defaultSetupOption = exports.defaultSerializer = exports.defaultLockGetOption = exports.defaultSetOption = exports.defaultRedisOption = void 0;
4
- exports.defaultRedisOption = {
1
+ export const defaultRedisOption = {
5
2
  host: process.env.REDIS_HOST || '127.0.0.1',
6
3
  port: parseInt(process.env.REDIS_PORT || '') || 6379,
7
4
  password: process.env.REDIS_PASSWORD || '',
8
5
  db: parseInt(process.env.REDIS_DB || '') || 0,
9
6
  };
10
- exports.defaultSetOption = {
7
+ export const defaultSetOption = {
11
8
  ttl: 60,
12
9
  compressMinLength: 1024,
13
10
  compressStoreRatio: 0.95,
14
11
  compressLevel: 1,
15
12
  };
16
- exports.defaultLockGetOption = {
13
+ export const defaultLockGetOption = {
17
14
  retryTimeout: 5000,
18
15
  retryDelay: 500,
19
16
  preRefresh: 0,
20
17
  refresh: false,
21
18
  localStore: undefined,
22
19
  };
23
- exports.defaultSerializer = {
20
+ export const defaultSerializer = {
24
21
  serialize: (data) => {
25
22
  return Buffer.from(JSON.stringify(data));
26
23
  },
@@ -28,9 +25,9 @@ exports.defaultSerializer = {
28
25
  return JSON.parse(data.toString());
29
26
  },
30
27
  };
31
- exports.defaultSetupOption = {
32
- redis: exports.defaultRedisOption,
33
- set: exports.defaultSetOption,
34
- lockGet: exports.defaultLockGetOption,
35
- serializer: exports.defaultSerializer,
28
+ export const defaultSetupOption = {
29
+ redis: defaultRedisOption,
30
+ set: defaultSetOption,
31
+ lockGet: defaultLockGetOption,
32
+ serializer: defaultSerializer,
36
33
  };
package/dist/types.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { Redis, RedisOptions } from "ioredis";
3
2
  /**
4
3
  * 缓存选项
package/dist/types.js CHANGED
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
package/dist/utils.js CHANGED
@@ -1,20 +1,16 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.cacheKey = exports.runRedisScript = exports.sleep = exports.debug = void 0;
4
- const core_1 = require("@zenweb/core");
5
- const crypto = require("crypto");
6
- exports.debug = (0, core_1.zenwebDebug)('cache');
1
+ import { zenwebDebug } from '@zenweb/core';
2
+ import * as crypto from 'node:crypto';
3
+ export const debug = zenwebDebug('cache');
7
4
  /**
8
5
  * Promise 等待
9
6
  * @param ms 毫秒
10
7
  * @returns
11
8
  */
12
- function sleep(ms) {
9
+ export function sleep(ms) {
13
10
  return new Promise((resolve) => {
14
11
  setTimeout(resolve, ms);
15
12
  });
16
13
  }
17
- exports.sleep = sleep;
18
14
  /**
19
15
  * 执行 Redis Lua 脚本
20
16
  * @param redis Redis 实例
@@ -24,14 +20,14 @@ exports.sleep = sleep;
24
20
  * @param values 输入值
25
21
  * @returns 执行结果
26
22
  */
27
- async function runRedisScript(redis, hash, script, keys, values = []) {
23
+ export async function runRedisScript(redis, hash, script, keys, values = []) {
28
24
  try {
29
25
  const result = await redis.evalsha(hash, keys.length, ...keys, ...values);
30
26
  return result;
31
27
  }
32
28
  catch (err) {
33
29
  if (err instanceof Error && err.message.includes('NOSCRIPT')) {
34
- (0, exports.debug)('runRedisScript: NOSCRIPT');
30
+ debug('runRedisScript: NOSCRIPT');
35
31
  // 缺少预设脚本,设置
36
32
  const result = await redis.eval(script, keys.length, ...keys, ...values);
37
33
  return result;
@@ -39,7 +35,6 @@ async function runRedisScript(redis, hash, script, keys, values = []) {
39
35
  throw err;
40
36
  }
41
37
  }
42
- exports.runRedisScript = runRedisScript;
43
38
  /**
44
39
  * 将一个嵌套对象转换为平面字符串结构
45
40
  */
@@ -69,7 +64,7 @@ function plainifyOrHash(obj) {
69
64
  * 生成一个参数缓存key
70
65
  * - 多个元素用 : 连接
71
66
  */
72
- function cacheKey(...key) {
67
+ export function cacheKey(...key) {
73
68
  return key.map(i => {
74
69
  if (typeof i === 'string')
75
70
  return i;
@@ -82,4 +77,3 @@ function cacheKey(...key) {
82
77
  return plainifyOrHash(i);
83
78
  }).join(':');
84
79
  }
85
- exports.cacheKey = cacheKey;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zenweb/cache",
3
- "packageManager": "yarn@4.0.2",
4
- "version": "4.7.1",
3
+ "type": "module",
4
+ "version": "5.0.0",
5
5
  "description": "Zenweb Cache module",
6
6
  "exports": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -9,11 +9,10 @@
9
9
  "dist"
10
10
  ],
11
11
  "scripts": {
12
- "vscode": "yarn dlx @yarnpkg/sdks vscode",
13
12
  "build": "rimraf dist && tsc",
14
- "prepack": "yarn run build",
15
- "test": "ts-mocha -p tsconfig.json test/**/*.test.ts",
16
- "dev": "cd example && cross-env DEBUG=\\* NODE_ENV=development ts-node app"
13
+ "prepack": "npm run build",
14
+ "test": "mocha --loader ts-node/esm -p tsconfig.json test/**/*.test.ts",
15
+ "dev": "cd example && cross-env DEBUG=\\* NODE_ENV=development node --loader ts-node/esm app.ts"
17
16
  },
18
17
  "author": {
19
18
  "name": "YeFei",
@@ -38,14 +37,13 @@
38
37
  "mocha": "^10.2.0",
39
38
  "msgpackr": "^1.11.0",
40
39
  "rimraf": "^4.3.1",
41
- "ts-mocha": "^10.0.0",
42
40
  "ts-node": "^10.9.1",
43
- "typescript": "^5.3.3",
44
- "zenweb": "^4.2.7"
41
+ "typescript": "^5.6.3",
42
+ "zenweb": "^5.1.0"
45
43
  },
46
44
  "dependencies": {
47
- "@zenweb/core": "^4.2.3",
48
- "@zenweb/result": "^4.1.2",
45
+ "@zenweb/core": "^5.1.0",
46
+ "@zenweb/result": "^5.0.0",
49
47
  "ioredis": "^5.3.2"
50
48
  }
51
49
  }