@knaus94/prisma-extension-cache-manager 1.5.62 → 1.5.63

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.d.ts CHANGED
@@ -4,7 +4,7 @@ import { ModelExtension, PrismaRedisCacheConfig } from "./types";
4
4
  * @param config - Конфигурация для кеша Redis и TTL по умолчанию.
5
5
  * @returns Prisma расширение.
6
6
  */
7
- declare const _default: ({ cache, defaultTTL, debug }: PrismaRedisCacheConfig) => (client: any) => import("@prisma/client/extension").PrismaClientExtends<import("@prisma/client/runtime/library").InternalArgs<{}, {
7
+ declare const _default: ({ cache, debug }: PrismaRedisCacheConfig) => (client: any) => import("@prisma/client/extension").PrismaClientExtends<import("@prisma/client/runtime/library").InternalArgs<{}, {
8
8
  $allModels: ModelExtension;
9
9
  }, {}, {
10
10
  $cache: import("cache-manager-ioredis-yet").RedisCache;
package/dist/index.js CHANGED
@@ -7,35 +7,24 @@ const types_1 = require("./types");
7
7
  const crypto_1 = require("crypto");
8
8
  const library_1 = require("@prisma/client/runtime/library");
9
9
  const extension_1 = require("@prisma/client/extension");
10
- // Импорт msgpack5
11
- const msgpack5_1 = __importDefault(require("msgpack5"));
10
+ const msgpack_lite_1 = __importDefault(require("msgpack-lite"));
12
11
  /**
13
- * Создаем экземпляр msgpack5.
12
+ * Создаем codec
14
13
  * В дальнейшем используем его encode/decode для сериализации/десериализации.
15
14
  */
16
- const mp = (0, msgpack5_1.default)();
17
- /**
18
- * Уникальные коды (type) для регистрации пользовательских типов
19
- * в MessagePack. Убедитесь, что числа не конфликтуют с другими типами.
20
- */
21
- const TYPE_DATE = 0x01;
22
- const TYPE_DECIMAL = 0x02;
23
- /**
24
- * Регистрируем тип `Date`.
25
- * - При кодировании превращаем `Date` в строку (ISO).
26
- * - При декодировании восстанавливаем из строки обратно в `Date`.
27
- */
28
- mp.register(TYPE_DATE, Date, (date) => Buffer.from(date.toISOString()), // encode
29
- (buffer) => new Date(buffer.toString()) // decode
30
- );
15
+ const codec = msgpack_lite_1.default.createCodec();
16
+ const TYPE_DECIMAL = 0x21;
31
17
  /**
32
18
  * Регистрируем тип `Decimal`.
33
19
  * - При кодировании превращаем `Decimal` в строку.
34
20
  * - При декодировании восстанавливаем обратно в `Decimal`.
35
21
  */
36
- mp.register(TYPE_DECIMAL, library_1.Decimal, (decimal) => Buffer.from(decimal.toString()), // encode
37
- (buffer) => new library_1.Decimal(buffer.toString()) // decode
38
- );
22
+ codec.addExtPacker(TYPE_DECIMAL, library_1.Decimal, (decimal) => {
23
+ return Buffer.from(decimal.toString());
24
+ });
25
+ codec.addExtUnpacker(TYPE_DECIMAL, (buffer) => {
26
+ return new library_1.Decimal(buffer.toString());
27
+ });
39
28
  /**
40
29
  * Генерирует уникальный ключ для кеширования на основе модели и аргументов запроса.
41
30
  * @param options - Опции для генерации ключа.
@@ -56,11 +45,17 @@ function generateComposedKey(options) {
56
45
  function createKey(key, namespace) {
57
46
  return namespace ? `${namespace}:${key}` : key;
58
47
  }
48
+ /**
49
+ * Сериализация данных с помощью msgpack-lite.
50
+ */
59
51
  function serialize(data) {
60
- return mp.encode(data).slice();
52
+ return msgpack_lite_1.default.encode(data, { codec });
61
53
  }
54
+ /**
55
+ * Десериализация данных с помощью msgpack-lite.
56
+ */
62
57
  function deserialize(buffer) {
63
- return mp.decode(buffer);
58
+ return msgpack_lite_1.default.decode(buffer, { codec });
64
59
  }
65
60
  /**
66
61
  * Обрабатывает удаление ключей из кеша после операций записи.
@@ -126,7 +121,7 @@ function shouldUseUncache(uncacheOption) {
126
121
  * @param config - Конфигурация для кеша Redis и TTL по умолчанию.
127
122
  * @returns Prisma расширение.
128
123
  */
129
- exports.default = ({ cache, defaultTTL, debug }) => {
124
+ exports.default = ({ cache, debug }) => {
130
125
  return extension_1.Prisma.defineExtension({
131
126
  name: "prisma-extension-cache-manager",
132
127
  client: {
@@ -179,8 +174,7 @@ exports.default = ({ cache, defaultTTL, debug }) => {
179
174
  ? cacheOption // Если cacheOption — строка, используем её как ключ напрямую
180
175
  : generateComposedKey({ model, queryArgs }); // Иначе генерируем ключ
181
176
  // Если cacheOption — число, оно означает TTL
182
- ttl =
183
- typeof cacheOption === "number" ? cacheOption : defaultTTL ?? 0;
177
+ ttl = typeof cacheOption === "number" ? cacheOption : undefined;
184
178
  }
185
179
  // 2b) Если cacheOption — объект с key: function,
186
180
  // нужно сначала сделать запрос к БД, чтобы функция могла сгенерировать ключ
@@ -193,17 +187,13 @@ exports.default = ({ cache, defaultTTL, debug }) => {
193
187
  }
194
188
  // Функция генерирует ключ на основе результатов
195
189
  cacheKey = cacheOption.key(result);
196
- ttl = cacheOption.ttl ?? defaultTTL ?? 0;
197
- // Сохраняем результат в кеш, используя msgpack5
190
+ ttl = cacheOption.ttl;
191
+ // Сохраняем результат в кеш
198
192
  try {
199
- if (ttl > 0) {
200
- await cache.store.client.set(cacheKey, serialize(result), "EX", ttl / 1000);
201
- }
202
- else {
203
- await cache.store.client.set(cacheKey, serialize(result));
204
- }
193
+ const encoded = serialize(result);
194
+ await cache.set(cacheKey, encoded);
205
195
  if (debug) {
206
- console.log("Data cached with key (function):", cacheKey, "encoded:", serialize(result), "decoded:", result);
196
+ console.log("Data cached with key (function):", cacheKey, "encoded:", encoded, "decoded:", result);
207
197
  }
208
198
  }
209
199
  catch (e) {
@@ -213,24 +203,23 @@ exports.default = ({ cache, defaultTTL, debug }) => {
213
203
  }
214
204
  return result;
215
205
  }
216
- // 2c) Иначе берем ключ/namespace/ttl из объекта
206
+ // 2c) Иначе берём ключ/namespace/ttl из объекта
217
207
  else {
218
208
  cacheKey =
219
209
  createKey(cacheOption.key, cacheOption.namespace) ||
220
210
  generateComposedKey({ model, queryArgs });
221
- ttl = cacheOption.ttl ?? defaultTTL;
211
+ ttl = cacheOption.ttl;
222
212
  }
223
213
  // 3. Если это операция чтения, пробуем вернуть данные из кеша
224
214
  if (!isWriteOperation) {
225
215
  try {
226
216
  // Используем getBuffer, т.к. сохраняем бинарные данные
227
- const cached = await cache.store.client.getBuffer(cacheKey);
217
+ const cached = await cache.get(cacheKey);
228
218
  if (cached) {
229
219
  const data = deserialize(cached);
230
220
  if (debug) {
231
221
  console.log("Cache hit for key:", cacheKey, "data", cached, "decoded", data);
232
222
  }
233
- // Десериализуем через msgpack5
234
223
  return data;
235
224
  }
236
225
  else {
@@ -253,15 +242,10 @@ exports.default = ({ cache, defaultTTL, debug }) => {
253
242
  }
254
243
  // 6. Сохраняем результат запроса в кеш
255
244
  try {
256
- const data = serialize(result);
257
- if (ttl > 0) {
258
- await cache.store.client.set(cacheKey, data, "EX", ttl / 1000);
259
- }
260
- else {
261
- await cache.store.client.set(cacheKey, data);
262
- }
245
+ const encoded = serialize(result);
246
+ await cache.set(cacheKey, encoded, ttl);
263
247
  if (debug) {
264
- console.log("Data cached with key:", cacheKey, "encoded:", data, "decoded:", result);
248
+ console.log("Data cached with key:", cacheKey, "encoded:", encoded, "decoded:", result);
265
249
  }
266
250
  }
267
251
  catch (e) {
package/dist/types.d.ts CHANGED
@@ -35,7 +35,6 @@ export interface PrismaCacheArgs<T, A, O extends RequiredArgsOperation | Optiona
35
35
  }
36
36
  export interface PrismaRedisCacheConfig {
37
37
  cache: RedisCache;
38
- defaultTTL?: number;
39
38
  debug?: boolean;
40
39
  }
41
40
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@knaus94/prisma-extension-cache-manager",
3
- "version": "1.5.62",
3
+ "version": "1.5.63",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/knaus94/prisma-extension-cache-manager.git"
@@ -40,7 +40,7 @@
40
40
  "test": "echo \"Error: no test specified\" && exit 1"
41
41
  },
42
42
  "devDependencies": {
43
- "@types/msgpack5": "^3.4.6",
43
+ "@types/msgpack-lite": "^0.1.11",
44
44
  "@types/node": "^20.10.6",
45
45
  "prettier": "^3.1.1",
46
46
  "rimraf": "^5.0.5",
@@ -55,9 +55,9 @@
55
55
  ]
56
56
  },
57
57
  "dependencies": {
58
- "msgpack5": "^6.0.2",
59
58
  "@prisma/client": "^5.7.1",
60
59
  "cache-manager": "^5.2.3",
61
- "cache-manager-ioredis-yet": "^2.1.1"
60
+ "cache-manager-ioredis-yet": "^2.1.1",
61
+ "msgpack-lite": "^0.1.26"
62
62
  }
63
63
  }