@akanjs/nest 0.0.19 → 0.0.21

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/nest",
3
- "version": "0.0.19",
3
+ "version": "0.0.21",
4
4
  "type": "commonjs",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -3,12 +3,10 @@ import { CallHandler, ExecutionContext, NestInterceptor } from "@nestjs/common";
3
3
  import type { RedisClientType } from "redis";
4
4
  import { Observable } from "rxjs";
5
5
  export declare class CacheInterceptor implements NestInterceptor {
6
- private redis;
7
- logger: Logger;
8
- constructor(redis: RedisClientType);
9
- setCache(key: string, value: any, expire: number): Promise<void>;
10
- getCache<T = object>(key: string): Promise<T | null>;
11
- intercept(context: ExecutionContext, next: CallHandler): Observable<any>;
6
+ #private;
7
+ private readonly redis;
8
+ constructor(redis: RedisClientType<any, any, any>);
9
+ intercept<T>(context: ExecutionContext, next: CallHandler): Promise<Observable<T>>;
12
10
  }
13
11
  export declare class TimeoutInterceptor implements NestInterceptor {
14
12
  intercept(context: ExecutionContext, next: CallHandler): Observable<any>;
@@ -6,11 +6,11 @@ var __export = (target, all) => {
6
6
  for (var name in all)
7
7
  __defProp(target, name, { get: all[name], enumerable: true });
8
8
  };
9
- var __copyProps = (to, from2, except, desc) => {
10
- if (from2 && typeof from2 === "object" || typeof from2 === "function") {
11
- for (let key of __getOwnPropNames(from2))
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
12
  if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable });
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
14
  }
15
15
  return to;
16
16
  };
@@ -25,6 +25,23 @@ var __decorateClass = (decorators, target, key, kind) => {
25
25
  return result;
26
26
  };
27
27
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
28
+ var __accessCheck = (obj, member, msg) => {
29
+ if (!member.has(obj))
30
+ throw TypeError("Cannot " + msg);
31
+ };
32
+ var __privateGet = (obj, member, getter) => {
33
+ __accessCheck(obj, member, "read from private field");
34
+ return getter ? getter.call(obj) : member.get(obj);
35
+ };
36
+ var __privateAdd = (obj, member, value) => {
37
+ if (member.has(obj))
38
+ throw TypeError("Cannot add the same private member more than once");
39
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
40
+ };
41
+ var __privateMethod = (obj, member, method) => {
42
+ __accessCheck(obj, member, "access private method");
43
+ return method;
44
+ };
28
45
  var interceptors_exports = {};
29
46
  __export(interceptors_exports, {
30
47
  CacheInterceptor: () => CacheInterceptor,
@@ -39,45 +56,84 @@ var import_graphql = require("@nestjs/graphql");
39
56
  var import_rxjs = require("rxjs");
40
57
  var import_operators = require("rxjs/operators");
41
58
  var import_authGuards = require("./authGuards");
59
+ var _logger, _CACHE_PREFIX, _generateCacheKey, generateCacheKey_fn, _getCache, getCache_fn, _setCache, setCache_fn;
42
60
  let CacheInterceptor = class {
43
61
  constructor(redis) {
44
62
  this.redis = redis;
63
+ __privateAdd(this, _generateCacheKey);
64
+ __privateAdd(this, _getCache);
65
+ __privateAdd(this, _setCache);
66
+ __privateAdd(this, _logger, new import_common.Logger("CacheInterceptor"));
67
+ __privateAdd(this, _CACHE_PREFIX, "signal:");
45
68
  }
46
- logger = new import_common.Logger("CacheInterceptor");
47
- async setCache(key, value, expire) {
48
- await this.redis.set(key, JSON.stringify(value), { PX: expire });
49
- }
50
- async getCache(key) {
51
- const cached = await this.redis.get(key);
52
- return cached ? JSON.parse(cached) : null;
53
- }
54
- intercept(context, next) {
55
- const signalKey = context.getHandler().name;
69
+ async intercept(context, next) {
70
+ const handler = context.getHandler();
71
+ const signalKey = handler.name;
56
72
  const gqlMeta = (0, import_signal.getGqlMeta)(context.getClass(), signalKey);
57
- const cacheExpireMs = gqlMeta.signalOption.cache;
58
- if (gqlMeta.type !== "Query" || !cacheExpireMs) {
59
- if (cacheExpireMs)
60
- this.logger.warn(`CacheInterceptor: ${signalKey} is not Query endpoint or cache is not set`);
73
+ if (gqlMeta.type !== "Query" || !gqlMeta.signalOption.cache) {
74
+ if (gqlMeta.signalOption.cache) {
75
+ __privateGet(this, _logger).warn(`CacheInterceptor: ${signalKey} is not Query endpoint or cache is not set`);
76
+ }
61
77
  return next.handle();
62
78
  }
63
79
  const args = (0, import_authGuards.getArgs)(context);
64
- const cacheKey = `signal:${signalKey}:${JSON.stringify(args)}`;
65
- const cacheResult$ = (0, import_rxjs.from)(this.getCache(cacheKey));
66
- return (0, import_rxjs.forkJoin)([cacheResult$]).pipe(
67
- (0, import_rxjs.switchMap)(([cacheResult]) => {
68
- if (cacheResult) {
69
- this.logger.trace(`CacheHit-${cacheKey}`);
70
- return (0, import_rxjs.of)(cacheResult);
71
- } else
72
- return next.handle().pipe(
73
- (0, import_rxjs.map)((resData) => {
74
- void this.setCache(cacheKey, resData, cacheExpireMs);
75
- this.logger.trace(`CacheSet-${cacheKey}`);
76
- return resData;
77
- })
78
- );
79
- })
80
- );
80
+ const cacheKey = __privateMethod(this, _generateCacheKey, generateCacheKey_fn).call(this, signalKey, args);
81
+ try {
82
+ const cachedData = await __privateMethod(this, _getCache, getCache_fn).call(this, cacheKey);
83
+ if (cachedData) {
84
+ __privateGet(this, _logger).debug(`Cache hit for key: ${cacheKey}`);
85
+ return (0, import_rxjs.of)(cachedData);
86
+ }
87
+ return next.handle().pipe(
88
+ (0, import_rxjs.map)((data) => {
89
+ const cacheDuration = gqlMeta.signalOption.cache;
90
+ if (typeof cacheDuration === "number") {
91
+ void __privateMethod(this, _setCache, setCache_fn).call(this, cacheKey, data, cacheDuration);
92
+ __privateGet(this, _logger).debug(`Cache set for key: ${cacheKey}`);
93
+ }
94
+ return data;
95
+ }),
96
+ (0, import_operators.catchError)((error) => {
97
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
98
+ __privateGet(this, _logger).error(`Error in cache interceptor for ${cacheKey}: ${errorMessage}`);
99
+ return (0, import_rxjs.throwError)(() => error);
100
+ })
101
+ );
102
+ } catch (error) {
103
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
104
+ __privateGet(this, _logger).error(`Cache error for ${cacheKey}: ${errorMessage}`);
105
+ return next.handle();
106
+ }
107
+ }
108
+ };
109
+ _logger = new WeakMap();
110
+ _CACHE_PREFIX = new WeakMap();
111
+ _generateCacheKey = new WeakSet();
112
+ generateCacheKey_fn = function(signalKey, args) {
113
+ return `${__privateGet(this, _CACHE_PREFIX)}${signalKey}:${JSON.stringify(args)}`;
114
+ };
115
+ _getCache = new WeakSet();
116
+ getCache_fn = async function(key) {
117
+ try {
118
+ const cached = await this.redis.get(key);
119
+ if (!cached)
120
+ return null;
121
+ const { data } = JSON.parse(cached);
122
+ return data;
123
+ } catch (error) {
124
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
125
+ __privateGet(this, _logger).error(`Error retrieving cache for key ${key}: ${errorMessage}`);
126
+ return null;
127
+ }
128
+ };
129
+ _setCache = new WeakSet();
130
+ setCache_fn = async function(key, data, ttlMs) {
131
+ try {
132
+ const cacheData = { data, timestamp: Date.now() };
133
+ await this.redis.set(key, JSON.stringify(cacheData), { PX: ttlMs });
134
+ } catch (error) {
135
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
136
+ __privateGet(this, _logger).error(`Error setting cache for key ${key}: ${errorMessage}`);
81
137
  }
82
138
  };
83
139
  CacheInterceptor = __decorateClass([