@knaus94/prisma-extension-cache-manager 1.5.67 → 1.5.68

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, debug, ttl: defaultTTL }: 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
@@ -1,19 +1,17 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  const types_1 = require("./types");
7
4
  const crypto_1 = require("crypto");
8
5
  const library_1 = require("@prisma/client/runtime/library");
9
6
  const extension_1 = require("@prisma/client/extension");
10
- const msgpack_lite_1 = __importDefault(require("msgpack-lite"));
7
+ const msgpack_lite_1 = require("msgpack-lite");
11
8
  /**
12
9
  * Создаем codec
13
10
  * В дальнейшем используем его encode/decode для сериализации/десериализации.
14
11
  */
15
- const codec = msgpack_lite_1.default.createCodec();
16
- const TYPE_DECIMAL = 0x21;
12
+ const codec = (0, msgpack_lite_1.createCodec)();
13
+ const TYPE_DECIMAL = 0x07;
14
+ const TYPE_DATE = 0x0d;
17
15
  /**
18
16
  * Регистрируем тип `Decimal`.
19
17
  * - При кодировании превращаем `Decimal` в строку.
@@ -25,6 +23,17 @@ codec.addExtPacker(TYPE_DECIMAL, library_1.Decimal, (decimal) => {
25
23
  codec.addExtUnpacker(TYPE_DECIMAL, (buffer) => {
26
24
  return new library_1.Decimal(buffer.toString());
27
25
  });
26
+ /**
27
+ * Регистрируем тип `Date`.
28
+ * - При кодировании превращаем `Date` в строку.
29
+ * - При декодировании восстанавливаем обратно в `Date`.
30
+ */
31
+ codec.addExtPacker(TYPE_DATE, Date, (date) => {
32
+ return Buffer.from(date.toISOString());
33
+ });
34
+ codec.addExtUnpacker(TYPE_DATE, (buffer) => {
35
+ return new Date(buffer.toString());
36
+ });
28
37
  /**
29
38
  * Генерирует уникальный ключ для кеширования на основе модели и аргументов запроса.
30
39
  * @param options - Опции для генерации ключа.
@@ -49,13 +58,13 @@ function createKey(key, namespace) {
49
58
  * Сериализация данных с помощью msgpack-lite.
50
59
  */
51
60
  function serialize(data) {
52
- return msgpack_lite_1.default.encode(data, { codec });
61
+ return (0, msgpack_lite_1.encode)(data, { codec });
53
62
  }
54
63
  /**
55
64
  * Десериализация данных с помощью msgpack-lite.
56
65
  */
57
66
  function deserialize(buffer) {
58
- return msgpack_lite_1.default.decode(buffer, { codec });
67
+ return (0, msgpack_lite_1.decode)(buffer, { codec });
59
68
  }
60
69
  /**
61
70
  * Обрабатывает удаление ключей из кеша после операций записи.
@@ -121,7 +130,7 @@ function shouldUseUncache(uncacheOption) {
121
130
  * @param config - Конфигурация для кеша Redis и TTL по умолчанию.
122
131
  * @returns Prisma расширение.
123
132
  */
124
- exports.default = ({ cache, debug, ttl: defaultTTL }) => {
133
+ exports.default = ({ cache, debug }) => {
125
134
  return extension_1.Prisma.defineExtension({
126
135
  name: "prisma-extension-cache-manager",
127
136
  client: {
@@ -188,15 +197,10 @@ exports.default = ({ cache, debug, ttl: defaultTTL }) => {
188
197
  // Функция генерирует ключ на основе результатов
189
198
  cacheKey = cacheOption.key(result);
190
199
  ttl = cacheOption.ttl;
191
- if (ttl === undefined) {
192
- ttl = defaultTTL;
193
- }
194
200
  // Сохраняем результат в кеш
195
201
  try {
196
202
  const encoded = serialize(result);
197
- await (ttl && ttl > 0
198
- ? cache.store.client.set(cacheKey, encoded, "EX", ttl / 1000)
199
- : await cache.store.client.set(cacheKey, encoded));
203
+ await cache.set(cacheKey, encoded, ttl);
200
204
  if (debug) {
201
205
  console.log("Data cached with key (function):", cacheKey, "encoded:", encoded, "decoded:", result);
202
206
  }
@@ -219,9 +223,9 @@ exports.default = ({ cache, debug, ttl: defaultTTL }) => {
219
223
  if (!isWriteOperation) {
220
224
  try {
221
225
  // Используем getBuffer, т.к. сохраняем бинарные данные
222
- const cached = await cache.store.client.getBuffer(cacheKey);
226
+ const cached = await cache.get(cacheKey);
223
227
  if (cached) {
224
- const data = deserialize(cached);
228
+ const data = deserialize(cached.data);
225
229
  if (debug) {
226
230
  console.log("Cache hit for key:", cacheKey, "data", cached, "decoded", data);
227
231
  }
@@ -245,15 +249,10 @@ exports.default = ({ cache, debug, ttl: defaultTTL }) => {
245
249
  if (useUncache) {
246
250
  await processUncache(cache, uncacheOption, result);
247
251
  }
248
- if (ttl === undefined) {
249
- ttl = defaultTTL;
250
- }
251
252
  // 6. Сохраняем результат запроса в кеш
252
253
  try {
253
254
  const encoded = serialize(result);
254
- await (ttl && ttl > 0
255
- ? cache.store.client.set(cacheKey, encoded, "EX", ttl / 1000)
256
- : await cache.store.client.set(cacheKey, encoded));
255
+ await cache.set(cacheKey, encoded, ttl);
257
256
  if (debug) {
258
257
  console.log("Data cached with key:", cacheKey, "encoded:", encoded, "decoded:", result);
259
258
  }
package/dist/types.d.ts CHANGED
@@ -36,6 +36,5 @@ export interface PrismaCacheArgs<T, A, O extends RequiredArgsOperation | Optiona
36
36
  export interface PrismaRedisCacheConfig {
37
37
  cache: RedisCache;
38
38
  debug?: boolean;
39
- ttl?: number;
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.67",
3
+ "version": "1.5.68",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/knaus94/prisma-extension-cache-manager.git"