@knaus94/prisma-extension-cache-manager 1.5.61 → 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,12 +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
- await cache.store.set(cacheKey, serialize(result), ttl);
193
+ const encoded = serialize(result);
194
+ await cache.set(cacheKey, encoded);
200
195
  if (debug) {
201
- 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);
202
197
  }
203
198
  }
204
199
  catch (e) {
@@ -208,24 +203,23 @@ exports.default = ({ cache, defaultTTL, debug }) => {
208
203
  }
209
204
  return result;
210
205
  }
211
- // 2c) Иначе берем ключ/namespace/ttl из объекта
206
+ // 2c) Иначе берём ключ/namespace/ttl из объекта
212
207
  else {
213
208
  cacheKey =
214
209
  createKey(cacheOption.key, cacheOption.namespace) ||
215
210
  generateComposedKey({ model, queryArgs });
216
- ttl = cacheOption.ttl ?? defaultTTL;
211
+ ttl = cacheOption.ttl;
217
212
  }
218
213
  // 3. Если это операция чтения, пробуем вернуть данные из кеша
219
214
  if (!isWriteOperation) {
220
215
  try {
221
216
  // Используем getBuffer, т.к. сохраняем бинарные данные
222
- const cached = await cache.store.client.getBuffer(cacheKey);
217
+ const cached = await cache.get(cacheKey);
223
218
  if (cached) {
224
219
  const data = deserialize(cached);
225
220
  if (debug) {
226
221
  console.log("Cache hit for key:", cacheKey, "data", cached, "decoded", data);
227
222
  }
228
- // Десериализуем через msgpack5
229
223
  return data;
230
224
  }
231
225
  else {
@@ -248,10 +242,10 @@ exports.default = ({ cache, defaultTTL, debug }) => {
248
242
  }
249
243
  // 6. Сохраняем результат запроса в кеш
250
244
  try {
251
- const data = serialize(result);
252
- await cache.store.set(cacheKey, data, ttl);
245
+ const encoded = serialize(result);
246
+ await cache.set(cacheKey, encoded, ttl);
253
247
  if (debug) {
254
- console.log("Data cached with key:", cacheKey, "encoded:", data, "decoded:", result);
248
+ console.log("Data cached with key:", cacheKey, "encoded:", encoded, "decoded:", result);
255
249
  }
256
250
  }
257
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.61",
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
  }