@baeta/cache-ioredis 2.0.0-next.14 → 2.0.0-next.15

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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @baeta/cache-ioredis
2
2
 
3
+ ## 2.0.0-next.15
4
+
5
+ ### Patch Changes
6
+
7
+ - Drop Node v23 and v25 by [@andreisergiu98](https://github.com/andreisergiu98) in [#474](https://github.com/andreisergiu98/baeta/pull/474)
8
+
9
+ - Use transactions when peristing queries by [@andreisergiu98](https://github.com/andreisergiu98) in [#495](https://github.com/andreisergiu98/baeta/pull/495)
10
+ - Updated dependencies [[`dc89e17`](https://github.com/andreisergiu98/baeta/commit/dc89e1728926f4bd5a5e1351635c38bf8d5938dc), [`b7d088a`](https://github.com/andreisergiu98/baeta/commit/b7d088a79cddf256216cf932d82a67d35fc4264f), [`2c303b2`](https://github.com/andreisergiu98/baeta/commit/2c303b217c87fe2c585cfe8d60c3e901d5fedbe1)]:
11
+ - @baeta/cache-redis-common@2.0.0-next.13
12
+ - @baeta/cache@2.0.0-next.15
13
+
3
14
  ## 2.0.0-next.14
4
15
 
5
16
  ### Patch Changes
package/README.md CHANGED
@@ -35,10 +35,11 @@ Building GraphQL APIs shouldn't be complicated. **Baeta** is a modern, modular,
35
35
  - **Middleware & Directives**: Easy integration of custom behaviors
36
36
  - **High Performance**: Built for scalability and efficiency
37
37
 
38
- #### And optional extensions and plugins
38
+ #### And optional app plugins and libraries
39
39
 
40
- - **@baeta/extension-auth**: Add powerful scope-based authorization
41
- - **@baeta/extension-cache**: Implement automatic caching with simple update patterns
40
+ - **@baeta/auth**: Add powerful scope-based authorization
41
+ - **@baeta/complexity**: Reject resource-exhausting queries with depth, breadth and complexity limits
42
+ - **@baeta/cache**: Type-safe caching with declarative queries and automatic reconciliation
42
43
  - ... and more!
43
44
 
44
45
  ## Why use Baeta?
@@ -89,7 +90,7 @@ const usersQuery = Query.users.resolve(() => {
89
90
  return dataSource.user.findMany();
90
91
  });
91
92
 
92
- Query.$fields({
93
+ export default Query.$fields({
93
94
  user: userQuery,
94
95
  users: usersQuery,
95
96
  });
@@ -98,17 +99,13 @@ Query.$fields({
98
99
  #### 3. Add authorization
99
100
 
100
101
  ```typescript
102
+ import { auth, rule, scope } from "./lib/auth.ts";
101
103
  import { UserModule } from "./typedef.ts";
102
104
 
103
105
  const { Query } = UserModule;
104
106
 
105
107
  const userQuery = Query.user
106
- .$auth({
107
- $or: {
108
- isPublic: true,
109
- isLoggedIn: true,
110
- },
111
- })
108
+ .$use(auth(rule.or(scope.isPublic, scope.isLoggedIn)))
112
109
  .resolve(async ({ args }) => {
113
110
  // ...
114
111
  });
@@ -117,23 +114,33 @@ const userQuery = Query.user
117
114
  #### 4. Add caching
118
115
 
119
116
  ```typescript
120
- const { Query, Mutation, User } = UserModule;
121
-
122
- export const userCache = User.$createCache();
123
-
124
- const userQuery = Query.user
125
- .$auth({
126
- // ...
117
+ import { createCache, defineQuery } from "@baeta/cache";
118
+ import { redisClient } from "./lib/redis.ts";
119
+
120
+ const { Query, Mutation } = UserModule;
121
+
122
+ export const userCache = createCache(redisClient, {
123
+ name: "UserCache",
124
+ parse: JSON.parse,
125
+ serialize: JSON.stringify,
126
+ })
127
+ .withQueries({
128
+ findUser: defineQuery({
129
+ resolve: async (args: { id: string }) => {
130
+ return dataSource.user.findUnique({ where: args });
131
+ },
132
+ }),
127
133
  })
128
- .$useCache(userCache)
129
- .resolve(async ({ args }) => {
130
- // ...
131
- });
134
+ .build();
135
+
136
+ const userQuery = Query.user.map(({ args }) =>
137
+ userCache.queries.findUser({ id: args.where.id }),
138
+ );
132
139
 
133
140
  const updateUserMutation = Mutation.updateUser
134
141
  .$use(async (next) => {
135
142
  const user = await next();
136
- await userCache.save(user);
143
+ if (user) await userCache.update(user);
137
144
  return user;
138
145
  })
139
146
  .resolve(async ({ args }) => {
package/dist/index.js CHANGED
@@ -46,15 +46,10 @@ var RedisCacheClient = class extends CacheClient {
46
46
  makePipeline: () => this.redis.pipeline(),
47
47
  addCommand: (pipeline, item) => {
48
48
  if (saveOptions.disableOverwrite !== true) pipeline.set(item.key, item.value, "PXAT", expiresAt);
49
- else {
50
- pipeline.setnx(item.key, item.value);
51
- pipeline.pexpireat(item.key, expiresAt);
52
- }
49
+ else pipeline.set(item.key, item.value, "PXAT", expiresAt, "NX");
53
50
  },
54
51
  executePipeline: async (pipeline) => {
55
- const result = await pipeline.exec();
56
- if (result == null) throw new Error("Unexpected null result from Redis pipeline");
57
- assertNoPipelineErrors(result);
52
+ assertNoPipelineErrors(await pipeline.exec());
58
53
  return [];
59
54
  },
60
55
  estimateSize: (item) => {
@@ -71,18 +66,19 @@ var RedisCacheClient = class extends CacheClient {
71
66
  async saveItemsWithDiff(items, options) {
72
67
  if (items.length === 0) return [];
73
68
  const expiresAt = Date.now() + options.ttlMs;
74
- const keys = new Array(items.length);
75
- const values = new Array(items.length);
76
- for (let i = 0; i < items.length; i++) {
77
- keys[i] = items[i][0];
78
- values[i] = options.serialize(items[i][1]);
69
+ const tx = this.redis.multi();
70
+ for (const item of items) {
71
+ tx.get(item[0]);
72
+ tx.set(item[0], options.serialize(item[1]), "PXAT", expiresAt);
79
73
  }
80
- const result = await this.scripts.saveWithDiffScript(keys, [...values, expiresAt.toString()]);
81
- if (!Array.isArray(result)) throw new Error(`Unexpected non-array result from Redis script: ${typeof result}`);
82
- return result.map((value) => {
83
- if (typeof value === "string") return options.parse(value);
84
- return null;
85
- });
74
+ const result = await tx.exec();
75
+ assertNoPipelineErrors(result);
76
+ const results = [];
77
+ for (let i = 0; i < result.length; i += 2) {
78
+ const value = result[i][1];
79
+ results.push(value == null ? null : options.parse(value));
80
+ }
81
+ return results;
86
82
  }
87
83
  async deleteItems(keys) {
88
84
  if (keys.length === 0) return;
@@ -92,12 +88,19 @@ var RedisCacheClient = class extends CacheClient {
92
88
  }
93
89
  async deleteItemsWithDiff(keys, options) {
94
90
  if (keys.length === 0) return [];
95
- const result = await this.scripts.deleteWithDiffScript(keys, []);
96
- if (!Array.isArray(result)) throw new Error(`Unexpected non-array result from Redis script: ${typeof result}`);
97
- return result.map((value) => {
98
- if (typeof value === "string") return options.parse(value);
99
- return null;
100
- });
91
+ const tx = this.redis.multi();
92
+ for (const key of keys) {
93
+ tx.get(key);
94
+ tx.unlink(key);
95
+ }
96
+ const result = await tx.exec();
97
+ assertNoPipelineErrors(result);
98
+ const results = [];
99
+ for (let i = 0; i < result.length; i += 2) {
100
+ const value = result[i][1];
101
+ results.push(value == null ? null : options.parse(value));
102
+ }
103
+ return results;
101
104
  }
102
105
  async getQuery(key, options) {
103
106
  const meta = await this.redis.get(key);
@@ -106,14 +109,14 @@ var RedisCacheClient = class extends CacheClient {
106
109
  async saveQuery(key, indexes, metadata, options) {
107
110
  const now = Date.now();
108
111
  const expiresAt = now + options.ttlMs;
109
- const pipeline = this.redis.pipeline();
110
- pipeline.set(key, options.serialize(metadata), "PXAT", expiresAt);
112
+ const tx = this.redis.multi();
113
+ tx.set(key, options.serialize(metadata), "PXAT", expiresAt);
111
114
  for (const indexKey of indexes) {
112
- pipeline.zadd(indexKey, expiresAt, key);
113
- pipeline.zremrangebyscore(indexKey, "-inf", now - INDEX_BUFFER_MS);
114
- pipeline.pexpireat(indexKey, expiresAt + INDEX_BUFFER_MS);
115
+ tx.zadd(indexKey, expiresAt, key);
116
+ tx.zremrangebyscore(indexKey, "-inf", now - INDEX_BUFFER_MS);
117
+ tx.pexpireat(indexKey, expiresAt + INDEX_BUFFER_MS);
115
118
  }
116
- assertNoPipelineErrors(await pipeline.exec());
119
+ assertNoPipelineErrors(await tx.exec());
117
120
  }
118
121
  async deleteQueries(indexes) {
119
122
  if (indexes.length === 0) return;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../lib/cache-client.ts"],"sourcesContent":["import {\n\tCacheClient,\n\ttype CacheClientSaveOptions,\n\ttype ItemCacheKey,\n\ttype QueryCacheIndexKey,\n\ttype QueryCacheKey,\n\ttype CacheClientArgs,\n\ttype CacheClientOptions,\n} from '@baeta/cache';\nimport {\n\tassertNoPipelineErrors,\n\tbatchPipeline,\n\tcreateRedisScripts,\n\ttype RedisScripts,\n} from '@baeta/cache-redis-common';\nimport { doBatched } from '@baeta/cache/sdk';\nimport type Redis from 'ioredis';\nimport type { Cluster as RedisCluster } from 'ioredis';\n\nconst INDEX_BUFFER_MS = 1_000;\nconst MAX_PIPELINE_SIZE_LIMIT = 50 * 1024 * 1024; // 50MB\nconst MAX_PIPELINE_COMMAND_LIMIT = 100_000;\nconst MAX_COMMAND_KEYS_LIMIT = 100_000;\n\nexport interface RedisCacheClientOptions extends CacheClientOptions {\n\t/**\n\t * Maximum total size of commands in a single pipeline batch. If the batch exceeds this size, it will be executed immediately.\n\t * @defaultValue 50 * 1024 * 1024 (50MB)\n\t */\n\tmaxPipelineSizeLimit?: number;\n\t/**\n\t * Maximum number of commands in a single pipeline batch. If the batch exceeds this number, it will be executed immediately.\n\t * @defaultValue 100_000\n\t */\n\tmaxPipelineCommandLimit?: number;\n\t/**\n\t * Maximum number of keys in a single command. If the number of keys exceeds this limit, multiple commands will be executed.\n\t * @defaultValue 100_000\n\t */\n\tmaxCommandKeysLimit?: number;\n}\n\nexport class RedisCacheClient extends CacheClient {\n\tredis: Redis | RedisCluster;\n\tprotected maxPipelineSizeLimit: number;\n\tprotected maxPipelineCommandLimit: number;\n\tprotected maxCommandKeysLimit: number;\n\tprotected scripts: RedisScripts;\n\n\tconstructor(redis: Redis | RedisCluster, options?: RedisCacheClientOptions) {\n\t\tsuper({\n\t\t\tnamespace: options?.namespace,\n\t\t\trevision: options?.revision,\n\t\t\tttlMs: options?.ttlMs,\n\t\t});\n\t\tthis.redis = redis;\n\t\tthis.maxPipelineSizeLimit = options?.maxPipelineSizeLimit ?? MAX_PIPELINE_SIZE_LIMIT;\n\t\tthis.maxPipelineCommandLimit = options?.maxPipelineCommandLimit ?? MAX_PIPELINE_COMMAND_LIMIT;\n\t\tthis.maxCommandKeysLimit = options?.maxCommandKeysLimit ?? MAX_COMMAND_KEYS_LIMIT;\n\t\tconst loadScript = async (script: string) => {\n\t\t\treturn await this.redis.script('LOAD', script);\n\t\t};\n\t\tconst evalSha = async (sha: string, keys: string[], args: string[]) => {\n\t\t\treturn await this.redis.evalsha(sha, keys.length, ...keys, ...args);\n\t\t};\n\t\tthis.scripts = createRedisScripts(loadScript, evalSha);\n\t}\n\n\tasync getPartialItems<Item>(\n\t\tkeys: ItemCacheKey[],\n\t\toptions: CacheClientArgs<Item>,\n\t): Promise<Array<Item | null>> {\n\t\tif (keys.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst values: Array<Item | null> = [];\n\t\tawait doBatched(keys, this.maxCommandKeysLimit, async (batch) => {\n\t\t\tconst batchValues = await this.redis.mget(batch);\n\t\t\tfor (const value of batchValues) {\n\t\t\t\tvalues.push(value == null ? null : options.parse(value));\n\t\t\t}\n\t\t});\n\t\treturn values;\n\t}\n\n\tasync saveItems<Item>(\n\t\titems: Array<[ItemCacheKey, Item]>,\n\t\toptions: CacheClientArgs<Item>,\n\t\tsaveOptions: CacheClientSaveOptions = {},\n\t): Promise<void> {\n\t\tif (items.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst expiresAt = Date.now() + options.ttlMs;\n\t\tconst serialized = items.map(([key, value]) => ({\n\t\t\tkey,\n\t\t\tvalue: options.serialize(value),\n\t\t}));\n\t\tawait batchPipeline({\n\t\t\tmakePipeline: () => this.redis.pipeline(),\n\t\t\taddCommand: (pipeline, item) => {\n\t\t\t\tif (saveOptions.disableOverwrite !== true) {\n\t\t\t\t\tpipeline.set(item.key, item.value, 'PXAT', expiresAt);\n\t\t\t\t} else {\n\t\t\t\t\tpipeline.setnx(item.key, item.value);\n\t\t\t\t\tpipeline.pexpireat(item.key, expiresAt);\n\t\t\t\t}\n\t\t\t},\n\t\t\texecutePipeline: async (pipeline) => {\n\t\t\t\tconst result = await pipeline.exec();\n\t\t\t\tif (result == null) {\n\t\t\t\t\tthrow new Error('Unexpected null result from Redis pipeline');\n\t\t\t\t}\n\t\t\t\tassertNoPipelineErrors(result);\n\t\t\t\treturn [];\n\t\t\t},\n\t\t\testimateSize: (item) => {\n\t\t\t\treturn item.key.length + item.value.length;\n\t\t\t},\n\t\t\titems: serialized,\n\t\t\tmaxBatchBytes: this.maxPipelineSizeLimit,\n\t\t\tmaxBatchCount: this.maxPipelineCommandLimit,\n\t\t});\n\t}\n\n\tasync saveItemsWithDiff<Item>(\n\t\titems: Array<[ItemCacheKey, Item]>,\n\t\toptions: CacheClientArgs<Item>,\n\t): Promise<Array<Item | null>> {\n\t\tif (items.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst expiresAt = Date.now() + options.ttlMs;\n\t\tconst keys: ItemCacheKey[] = new Array(items.length);\n\t\tconst values: string[] = new Array(items.length);\n\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\tkeys[i] = items[i][0];\n\t\t\tvalues[i] = options.serialize(items[i][1]);\n\t\t}\n\t\tconst result = await this.scripts.saveWithDiffScript(keys, [...values, expiresAt.toString()]);\n\t\tif (!Array.isArray(result)) {\n\t\t\tthrow new Error(`Unexpected non-array result from Redis script: ${typeof result}`);\n\t\t}\n\t\treturn result.map((value) => {\n\t\t\tif (typeof value === 'string') {\n\t\t\t\treturn options.parse(value);\n\t\t\t}\n\t\t\treturn null;\n\t\t});\n\t}\n\n\tasync deleteItems(keys: ItemCacheKey[]): Promise<void> {\n\t\tif (keys.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tawait doBatched(keys, this.maxCommandKeysLimit, async (batch) => {\n\t\t\tawait this.redis.unlink(batch);\n\t\t});\n\t}\n\n\tasync deleteItemsWithDiff<Item>(\n\t\tkeys: ItemCacheKey[],\n\t\toptions: CacheClientArgs<Item>,\n\t): Promise<Array<Item | null>> {\n\t\tif (keys.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst result = await this.scripts.deleteWithDiffScript(keys, []);\n\t\tif (!Array.isArray(result)) {\n\t\t\tthrow new Error(`Unexpected non-array result from Redis script: ${typeof result}`);\n\t\t}\n\t\treturn result.map((value) => {\n\t\t\tif (typeof value === 'string') {\n\t\t\t\treturn options.parse(value);\n\t\t\t}\n\t\t\treturn null;\n\t\t});\n\t}\n\n\tasync getQuery<QueryMetadata>(\n\t\tkey: QueryCacheKey,\n\t\toptions: CacheClientArgs<QueryMetadata>,\n\t): Promise<QueryMetadata | null> {\n\t\tconst meta = await this.redis.get(key);\n\t\treturn meta == null ? null : options.parse(meta);\n\t}\n\n\tasync saveQuery<QueryMetadata>(\n\t\tkey: QueryCacheKey,\n\t\tindexes: QueryCacheIndexKey[],\n\t\tmetadata: QueryMetadata,\n\t\toptions: CacheClientArgs<QueryMetadata>,\n\t): Promise<void> {\n\t\tconst now = Date.now();\n\t\tconst expiresAt = now + options.ttlMs;\n\t\tconst pipeline = this.redis.pipeline();\n\t\tpipeline.set(key, options.serialize(metadata), 'PXAT', expiresAt);\n\t\tfor (const indexKey of indexes) {\n\t\t\tpipeline.zadd(indexKey, expiresAt, key);\n\t\t\tpipeline.zremrangebyscore(indexKey, '-inf', now - INDEX_BUFFER_MS);\n\t\t\tpipeline.pexpireat(indexKey, expiresAt + INDEX_BUFFER_MS);\n\t\t}\n\t\tconst result = await pipeline.exec();\n\t\tassertNoPipelineErrors(result);\n\t}\n\n\tasync deleteQueries(indexes: QueryCacheIndexKey[]): Promise<void> {\n\t\tif (indexes.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst result = await this.scripts.deleteQueriesScript(indexes, []);\n\t\tif (typeof result !== 'number') {\n\t\t\tthrow new Error(`Unexpected non-number result from Redis script: ${typeof result}`);\n\t\t}\n\t}\n}\n"],"mappings":";;;;AAmBA,MAAM,kBAAkB;AACxB,MAAM,0BAA0B,KAAK,OAAO;AAC5C,MAAM,6BAA6B;AACnC,MAAM,yBAAyB;AAoB/B,IAAa,mB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;AAChE,MAAI,CAAC,MAAM,QAAQ,OAAO,CACzB,OAAM,IAAI,MAAM,kDAAkD,OAAO,SAAS;AAEnF,SAAO,OAAO,KAAK,UAAU;AAC5B,OAAI,OAAO,UAAU,SACpB,QAAO,QAAQ,MAAM,MAAM;AAE5B,UAAO;IACN;;CAGH,MAAM,SACL,KACA,SACgC;EAChC,MAAM,OAAO,MAAM,KAAK,MAAM,IAAI,IAAI;AACtC,SAAO,QAAQ,OAAO,OAAO,QAAQ,MAAM,KAAK;;CAGjD,MAAM,UACL,KACA,SACA,UACA,SACgB;EAChB,MAAM,MAAM,KAAK,KAAK;EACtB,MAAM,YAAY,MAAM,QAAQ;EAChC,MAAM,WAAW,KAAK,MAAM,UAAU;AACtC,WAAS,IAAI,KAAK,QAAQ,UAAU,SAAS,EAAE,QAAQ,UAAU;AACjE,OAAK,MAAM,YAAY,SAAS;AAC/B,YAAS,KAAK,UAAU,WAAW,IAAI;AACvC,YAAS,iBAAiB,UAAU,QAAQ,MAAM,gBAAgB;AAClE,YAAS,UAAU,UAAU,YAAY,gBAAgB;;AAG1D,yBAAuB,MADF,SAAS,MAAM,CACN;;CAG/B,MAAM,cAAc,SAA8C;AACjE,MAAI,QAAQ,WAAW,EACtB;EAED,MAAM,SAAS,MAAM,KAAK,QAAQ,oBAAoB,SAAS,EAAE,CAAC;AAClE,MAAI,OAAO,WAAW,SACrB,OAAM,IAAI,MAAM,mDAAmD,OAAO,SAAS"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../lib/cache-client.ts"],"sourcesContent":["import {\n\tCacheClient,\n\ttype CacheClientSaveOptions,\n\ttype ItemCacheKey,\n\ttype QueryCacheIndexKey,\n\ttype QueryCacheKey,\n\ttype CacheClientArgs,\n\ttype CacheClientOptions,\n} from '@baeta/cache';\nimport {\n\tassertNoPipelineErrors,\n\tbatchPipeline,\n\tcreateRedisScripts,\n\ttype RedisScripts,\n} from '@baeta/cache-redis-common';\nimport { doBatched } from '@baeta/cache/sdk';\nimport type Redis from 'ioredis';\nimport type { Cluster as RedisCluster } from 'ioredis';\n\nconst INDEX_BUFFER_MS = 1_000;\nconst MAX_PIPELINE_SIZE_LIMIT = 50 * 1024 * 1024; // 50MB\nconst MAX_PIPELINE_COMMAND_LIMIT = 100_000;\nconst MAX_COMMAND_KEYS_LIMIT = 100_000;\n\nexport interface RedisCacheClientOptions extends CacheClientOptions {\n\t/**\n\t * Maximum total size of commands in a single pipeline batch. If the batch exceeds this size, it will be executed immediately.\n\t * @defaultValue 50 * 1024 * 1024 (50MB)\n\t */\n\tmaxPipelineSizeLimit?: number;\n\t/**\n\t * Maximum number of commands in a single pipeline batch. If the batch exceeds this number, it will be executed immediately.\n\t * @defaultValue 100_000\n\t */\n\tmaxPipelineCommandLimit?: number;\n\t/**\n\t * Maximum number of keys in a single command. If the number of keys exceeds this limit, multiple commands will be executed.\n\t * @defaultValue 100_000\n\t */\n\tmaxCommandKeysLimit?: number;\n}\n\nexport class RedisCacheClient extends CacheClient {\n\tredis: Redis | RedisCluster;\n\tprotected maxPipelineSizeLimit: number;\n\tprotected maxPipelineCommandLimit: number;\n\tprotected maxCommandKeysLimit: number;\n\tprotected scripts: RedisScripts;\n\n\tconstructor(redis: Redis | RedisCluster, options?: RedisCacheClientOptions) {\n\t\tsuper({\n\t\t\tnamespace: options?.namespace,\n\t\t\trevision: options?.revision,\n\t\t\tttlMs: options?.ttlMs,\n\t\t});\n\t\tthis.redis = redis;\n\t\tthis.maxPipelineSizeLimit = options?.maxPipelineSizeLimit ?? MAX_PIPELINE_SIZE_LIMIT;\n\t\tthis.maxPipelineCommandLimit = options?.maxPipelineCommandLimit ?? MAX_PIPELINE_COMMAND_LIMIT;\n\t\tthis.maxCommandKeysLimit = options?.maxCommandKeysLimit ?? MAX_COMMAND_KEYS_LIMIT;\n\t\tconst loadScript = async (script: string) => {\n\t\t\treturn await this.redis.script('LOAD', script);\n\t\t};\n\t\tconst evalSha = async (sha: string, keys: string[], args: string[]) => {\n\t\t\treturn await this.redis.evalsha(sha, keys.length, ...keys, ...args);\n\t\t};\n\t\tthis.scripts = createRedisScripts(loadScript, evalSha);\n\t}\n\n\tasync getPartialItems<Item>(\n\t\tkeys: ItemCacheKey[],\n\t\toptions: CacheClientArgs<Item>,\n\t): Promise<Array<Item | null>> {\n\t\tif (keys.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst values: Array<Item | null> = [];\n\t\tawait doBatched(keys, this.maxCommandKeysLimit, async (batch) => {\n\t\t\tconst batchValues = await this.redis.mget(batch);\n\t\t\tfor (const value of batchValues) {\n\t\t\t\tvalues.push(value == null ? null : options.parse(value));\n\t\t\t}\n\t\t});\n\t\treturn values;\n\t}\n\n\tasync saveItems<Item>(\n\t\titems: Array<[ItemCacheKey, Item]>,\n\t\toptions: CacheClientArgs<Item>,\n\t\tsaveOptions: CacheClientSaveOptions = {},\n\t): Promise<void> {\n\t\tif (items.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst expiresAt = Date.now() + options.ttlMs;\n\t\tconst serialized = items.map(([key, value]) => ({\n\t\t\tkey,\n\t\t\tvalue: options.serialize(value),\n\t\t}));\n\t\tawait batchPipeline({\n\t\t\tmakePipeline: () => this.redis.pipeline(),\n\t\t\taddCommand: (pipeline, item) => {\n\t\t\t\tif (saveOptions.disableOverwrite !== true) {\n\t\t\t\t\tpipeline.set(item.key, item.value, 'PXAT', expiresAt);\n\t\t\t\t} else {\n\t\t\t\t\tpipeline.set(item.key, item.value, 'PXAT', expiresAt, 'NX');\n\t\t\t\t}\n\t\t\t},\n\t\t\texecutePipeline: async (pipeline) => {\n\t\t\t\tconst result = await pipeline.exec();\n\t\t\t\tassertNoPipelineErrors(result);\n\t\t\t\treturn [];\n\t\t\t},\n\t\t\testimateSize: (item) => {\n\t\t\t\treturn item.key.length + item.value.length;\n\t\t\t},\n\t\t\titems: serialized,\n\t\t\tmaxBatchBytes: this.maxPipelineSizeLimit,\n\t\t\tmaxBatchCount: this.maxPipelineCommandLimit,\n\t\t});\n\t}\n\n\tasync saveItemsWithDiff<Item>(\n\t\titems: Array<[ItemCacheKey, Item]>,\n\t\toptions: CacheClientArgs<Item>,\n\t): Promise<Array<Item | null>> {\n\t\tif (items.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst expiresAt = Date.now() + options.ttlMs;\n\t\tconst tx = this.redis.multi();\n\t\tfor (const item of items) {\n\t\t\ttx.get(item[0]);\n\t\t\ttx.set(item[0], options.serialize(item[1]), 'PXAT', expiresAt);\n\t\t}\n\t\tconst result = await tx.exec();\n\t\tassertNoPipelineErrors(result);\n\t\tconst results: Array<Item | null> = [];\n\t\tfor (let i = 0; i < result.length; i += 2) {\n\t\t\tconst value = result[i][1];\n\t\t\tresults.push(value == null ? null : options.parse(value as string));\n\t\t}\n\t\treturn results;\n\t}\n\n\tasync deleteItems(keys: ItemCacheKey[]): Promise<void> {\n\t\tif (keys.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tawait doBatched(keys, this.maxCommandKeysLimit, async (batch) => {\n\t\t\tawait this.redis.unlink(batch);\n\t\t});\n\t}\n\n\tasync deleteItemsWithDiff<Item>(\n\t\tkeys: ItemCacheKey[],\n\t\toptions: CacheClientArgs<Item>,\n\t): Promise<Array<Item | null>> {\n\t\tif (keys.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst tx = this.redis.multi();\n\t\tfor (const key of keys) {\n\t\t\ttx.get(key);\n\t\t\ttx.unlink(key);\n\t\t}\n\t\tconst result = await tx.exec();\n\t\tassertNoPipelineErrors(result);\n\t\tconst results: Array<Item | null> = [];\n\t\tfor (let i = 0; i < result.length; i += 2) {\n\t\t\tconst value = result[i][1];\n\t\t\tresults.push(value == null ? null : options.parse(value as string));\n\t\t}\n\t\treturn results;\n\t}\n\n\tasync getQuery<QueryMetadata>(\n\t\tkey: QueryCacheKey,\n\t\toptions: CacheClientArgs<QueryMetadata>,\n\t): Promise<QueryMetadata | null> {\n\t\tconst meta = await this.redis.get(key);\n\t\treturn meta == null ? null : options.parse(meta);\n\t}\n\n\tasync saveQuery<QueryMetadata>(\n\t\tkey: QueryCacheKey,\n\t\tindexes: QueryCacheIndexKey[],\n\t\tmetadata: QueryMetadata,\n\t\toptions: CacheClientArgs<QueryMetadata>,\n\t): Promise<void> {\n\t\tconst now = Date.now();\n\t\tconst expiresAt = now + options.ttlMs;\n\t\tconst tx = this.redis.multi();\n\t\ttx.set(key, options.serialize(metadata), 'PXAT', expiresAt);\n\t\tfor (const indexKey of indexes) {\n\t\t\ttx.zadd(indexKey, expiresAt, key);\n\t\t\ttx.zremrangebyscore(indexKey, '-inf', now - INDEX_BUFFER_MS);\n\t\t\ttx.pexpireat(indexKey, expiresAt + INDEX_BUFFER_MS);\n\t\t}\n\t\tconst result = await tx.exec();\n\t\tassertNoPipelineErrors(result);\n\t}\n\n\tasync deleteQueries(indexes: QueryCacheIndexKey[]): Promise<void> {\n\t\tif (indexes.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst result = await this.scripts.deleteQueriesScript(indexes, []);\n\t\tif (typeof result !== 'number') {\n\t\t\tthrow new Error(`Unexpected non-number result from Redis script: ${typeof result}`);\n\t\t}\n\t}\n}\n"],"mappings":";;;;AAmBA,MAAM,kBAAkB;AACxB,MAAM,0BAA0B,KAAK,OAAO;AAC5C,MAAM,6BAA6B;AACnC,MAAM,yBAAyB;AAoB/B,IAAa,mBAAb,cAAsC,YAAY;CACjD;CACA;CACA;CACA;CACA;CAEA,YAAY,OAA6B,SAAmC;EAC3E,MAAM;GACL,WAAW,SAAS;GACpB,UAAU,SAAS;GACnB,OAAO,SAAS;EACjB,CAAC;EACD,KAAK,QAAQ;EACb,KAAK,uBAAuB,SAAS,wBAAwB;EAC7D,KAAK,0BAA0B,SAAS,2BAA2B;EACnE,KAAK,sBAAsB,SAAS,uBAAuB;EAC3D,MAAM,aAAa,OAAO,WAAmB;GAC5C,OAAO,MAAM,KAAK,MAAM,OAAO,QAAQ,MAAM;EAC9C;EACA,MAAM,UAAU,O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AM,KAAK,IAAI;EACrB,MAAM,YAAY,MAAM,QAAQ;EAChC,MAAM,KAAK,KAAK,MAAM,MAAM;EAC5B,GAAG,IAAI,KAAK,QAAQ,UAAU,QAAQ,GAAG,QAAQ,SAAS;EAC1D,KAAK,MAAM,YAAY,SAAS;GAC/B,GAAG,KAAK,UAAU,WAAW,GAAG;GAChC,GAAG,iBAAiB,UAAU,QAAQ,MAAM,eAAe;GAC3D,GAAG,UAAU,UAAU,YAAY,eAAe;EACnD;EAEA,uBAAuB,MADF,GAAG,KAAK,CACA;CAC9B;CAEA,MAAM,cAAc,SAA8C;EACjE,IAAI,QAAQ,WAAW,GACtB;EAED,MAAM,SAAS,MAAM,KAAK,QAAQ,oBAAoB,SAAS,CAAC,CAAC;EACjE,IAAI,OAAO,WAAW,UACrB,MAAM,IAAI,MAAM,mDAAmD,OAAO,QAAQ;CAEpF;AACD"}
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@baeta/cache-ioredis",
3
- "version": "2.0.0-next.14",
3
+ "version": "2.0.0-next.15",
4
+ "description": "ioredis cache adapter for Baeta.",
4
5
  "keywords": [
5
6
  "baeta",
6
7
  "builder",
@@ -21,14 +22,14 @@
21
22
  },
22
23
  "repository": {
23
24
  "type": "git",
24
- "url": "https://github.com/andreisergiu98/baeta.git",
25
+ "url": "git+https://github.com/andreisergiu98/baeta.git",
25
26
  "directory": "packages/cache-ioredis"
26
27
  },
27
28
  "files": [
28
- "dist",
29
- "package.json"
29
+ "dist"
30
30
  ],
31
31
  "type": "module",
32
+ "sideEffects": false,
32
33
  "types": "dist/index.d.ts",
33
34
  "exports": {
34
35
  ".": {
@@ -37,36 +38,36 @@
37
38
  }
38
39
  },
39
40
  "publishConfig": {
40
- "access": "public",
41
41
  "exports": {
42
42
  ".": {
43
43
  "types": "./dist/index.d.ts",
44
44
  "default": "./dist/index.js"
45
45
  }
46
- }
46
+ },
47
+ "access": "public"
47
48
  },
48
49
  "scripts": {
49
50
  "build": "builder build",
50
51
  "check:deps": "builder check-deps",
51
52
  "postpack": "builder prepare --restore",
52
53
  "prepack": "builder prepare",
53
- "test": "builder test --skip-coverage",
54
+ "test": "builder test",
54
55
  "types": "tsc --noEmit"
55
56
  },
56
57
  "dependencies": {
57
- "@baeta/cache-redis-common": "^2.0.0-next.12"
58
+ "@baeta/cache-redis-common": "^2.0.0-next.13"
58
59
  },
59
60
  "devDependencies": {
60
61
  "@baeta/builder": "^0.0.0",
61
- "@baeta/cache": "^2.0.0-next.14",
62
+ "@baeta/cache": "^2.0.0-next.15",
62
63
  "@baeta/testing": "^0.0.0",
63
64
  "@baeta/tests-cache-clients": "^0.0.0",
64
65
  "@baeta/tsconfig": "^0.0.0",
65
- "ioredis": "^5.10.1",
66
+ "ioredis": "^5.11.0",
66
67
  "typescript": "^6.0.0"
67
68
  },
68
69
  "peerDependencies": {
69
- "@baeta/cache": "^2.0.0-next.14",
70
+ "@baeta/cache": "^2.0.0-next.15",
70
71
  "ioredis": "^5.10.0"
71
72
  },
72
73
  "ava": {
@@ -75,7 +76,7 @@
75
76
  ]
76
77
  },
77
78
  "engines": {
78
- "node": ">=22.20.0"
79
+ "node": "^22.20.0 || ^24.0.0 || >=26.0.0"
79
80
  },
80
81
  "typedocOptions": {
81
82
  "entryPoints": [