@sebspark/promise-cache 0.2.2 → 0.2.4

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/README.md CHANGED
@@ -9,9 +9,15 @@ A simple caching wrapper for promises.
9
9
  import { PromiseCache } from '@sebspark/promise-cache'
10
10
 
11
11
  // Instantiate the cache with a TTL.
12
- const cache = new PromiseCache<string, number>(60) // 1 minute cache TTL.
12
+ const cache = new PromiseCache<number>(60, true, true) // 1 minute cache TTL / is case sensitive / use local storage
13
+
14
+ const redisCache = new PromiseCache<number>(60, false, false) // 1 minute cache TTL / is not case sensitive / use redis storage
13
15
 
14
16
  // Use the cache wrapper for a database query to relieve the database.
15
17
  const query = 'SELECT username FROM users ORDER BY created DESC LIMIT 1'
16
18
  const newestUser = await cache.wrap('newestUser', () => database.query(query))
17
- ```
19
+
20
+ // Use the cache wrapper for a database query to relieve the database.
21
+ const query = 'SELECT username FROM users ORDER BY created DESC LIMIT 1'
22
+ const newestUser = await redisCache.wrap('newestUserRedis', () => database.query(query))
23
+ ```
package/dist/index.d.mts CHANGED
@@ -1,20 +1,23 @@
1
+ import { createClient } from 'redis';
2
+
1
3
  type GetType<T> = {
2
4
  value: T;
3
- ttl: number;
5
+ ttl?: number;
4
6
  timestamp: number;
5
7
  };
6
8
  type SetParams<T> = {
7
9
  value: T;
8
10
  timestamp: number;
9
- ttl: number;
11
+ ttl?: number;
10
12
  };
11
13
  declare class Persistor {
12
- private client;
14
+ client: ReturnType<typeof createClient> | null;
13
15
  status: 'connected' | 'disconnected';
14
- constructor();
16
+ constructor(isLocalPersistor: boolean);
15
17
  connect(): Promise<void>;
16
18
  size(): Promise<number>;
17
19
  get<T>(key: string): Promise<GetType<T> | null>;
20
+ private createOptions;
18
21
  set<T>(key: string, { value, timestamp, ttl }: SetParams<T>): Promise<void>;
19
22
  delete(key: string): Promise<void>;
20
23
  }
@@ -22,13 +25,13 @@ declare class Persistor {
22
25
  declare class PromiseCache<U> {
23
26
  persistor: Persistor;
24
27
  private readonly caseSensitive;
25
- private readonly ttl;
28
+ private readonly ttl?;
26
29
  /**
27
30
  * Initialize a new PromiseCache.
28
31
  * @param ttlInSeconds Default cache TTL.
29
32
  * @param caseSensitive Set to true if you want to differentiate between keys with different casing.
30
33
  */
31
- constructor(ttlInSeconds: number, caseSensitive?: boolean);
34
+ constructor(ttlInSeconds?: number, caseSensitive?: boolean, isLocalPersistor?: boolean);
32
35
  /**
33
36
  * Cache size.
34
37
  * @returns The number of entries in the cache.
@@ -41,6 +44,11 @@ declare class PromiseCache<U> {
41
44
  * @param ttlInSeconds Time to live in seconds.
42
45
  */
43
46
  override<U>(key: string, value: U, ttlInSeconds?: number): Promise<void>;
47
+ /**
48
+ * Get a value from the cache.
49
+ * @param key Cache key.
50
+ */
51
+ find<U>(key: string): Promise<U | null>;
44
52
  /**
45
53
  * A simple promise cache wrapper.
46
54
  * @param key Cache key.
@@ -51,4 +59,18 @@ declare class PromiseCache<U> {
51
59
  wrap(key: string, delegate: () => Promise<U>, ttlInSeconds?: number): Promise<U>;
52
60
  }
53
61
 
54
- export { PromiseCache };
62
+ declare class LocalStorage {
63
+ client: Map<any, any>;
64
+ get(key: string): any;
65
+ set(key: string, value: string, options?: {
66
+ EX: number;
67
+ }): void;
68
+ del(key: string): void;
69
+ clear(): void;
70
+ DBSIZE(): Promise<number>;
71
+ on(event: string, callback: (message: string) => void): this;
72
+ connect(): Promise<this>;
73
+ }
74
+ declare const createLocalMemoryClient: () => LocalStorage;
75
+
76
+ export { LocalStorage, PromiseCache, createLocalMemoryClient };
package/dist/index.d.ts CHANGED
@@ -1,20 +1,23 @@
1
+ import { createClient } from 'redis';
2
+
1
3
  type GetType<T> = {
2
4
  value: T;
3
- ttl: number;
5
+ ttl?: number;
4
6
  timestamp: number;
5
7
  };
6
8
  type SetParams<T> = {
7
9
  value: T;
8
10
  timestamp: number;
9
- ttl: number;
11
+ ttl?: number;
10
12
  };
11
13
  declare class Persistor {
12
- private client;
14
+ client: ReturnType<typeof createClient> | null;
13
15
  status: 'connected' | 'disconnected';
14
- constructor();
16
+ constructor(isLocalPersistor: boolean);
15
17
  connect(): Promise<void>;
16
18
  size(): Promise<number>;
17
19
  get<T>(key: string): Promise<GetType<T> | null>;
20
+ private createOptions;
18
21
  set<T>(key: string, { value, timestamp, ttl }: SetParams<T>): Promise<void>;
19
22
  delete(key: string): Promise<void>;
20
23
  }
@@ -22,13 +25,13 @@ declare class Persistor {
22
25
  declare class PromiseCache<U> {
23
26
  persistor: Persistor;
24
27
  private readonly caseSensitive;
25
- private readonly ttl;
28
+ private readonly ttl?;
26
29
  /**
27
30
  * Initialize a new PromiseCache.
28
31
  * @param ttlInSeconds Default cache TTL.
29
32
  * @param caseSensitive Set to true if you want to differentiate between keys with different casing.
30
33
  */
31
- constructor(ttlInSeconds: number, caseSensitive?: boolean);
34
+ constructor(ttlInSeconds?: number, caseSensitive?: boolean, isLocalPersistor?: boolean);
32
35
  /**
33
36
  * Cache size.
34
37
  * @returns The number of entries in the cache.
@@ -41,6 +44,11 @@ declare class PromiseCache<U> {
41
44
  * @param ttlInSeconds Time to live in seconds.
42
45
  */
43
46
  override<U>(key: string, value: U, ttlInSeconds?: number): Promise<void>;
47
+ /**
48
+ * Get a value from the cache.
49
+ * @param key Cache key.
50
+ */
51
+ find<U>(key: string): Promise<U | null>;
44
52
  /**
45
53
  * A simple promise cache wrapper.
46
54
  * @param key Cache key.
@@ -51,4 +59,18 @@ declare class PromiseCache<U> {
51
59
  wrap(key: string, delegate: () => Promise<U>, ttlInSeconds?: number): Promise<U>;
52
60
  }
53
61
 
54
- export { PromiseCache };
62
+ declare class LocalStorage {
63
+ client: Map<any, any>;
64
+ get(key: string): any;
65
+ set(key: string, value: string, options?: {
66
+ EX: number;
67
+ }): void;
68
+ del(key: string): void;
69
+ clear(): void;
70
+ DBSIZE(): Promise<number>;
71
+ on(event: string, callback: (message: string) => void): this;
72
+ connect(): Promise<this>;
73
+ }
74
+ declare const createLocalMemoryClient: () => LocalStorage;
75
+
76
+ export { LocalStorage, PromiseCache, createLocalMemoryClient };
package/dist/index.js CHANGED
@@ -20,24 +20,73 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
- PromiseCache: () => PromiseCache
23
+ LocalStorage: () => LocalStorage,
24
+ PromiseCache: () => PromiseCache,
25
+ createLocalMemoryClient: () => createLocalMemoryClient
24
26
  });
25
27
  module.exports = __toCommonJS(src_exports);
26
28
 
27
29
  // src/persistor.ts
28
30
  var import_redis = require("redis");
31
+
32
+ // src/localMemory.ts
33
+ var LocalStorage = class {
34
+ client = /* @__PURE__ */ new Map();
35
+ get(key) {
36
+ return this.client.get(key);
37
+ }
38
+ set(key, value, options) {
39
+ this.client.set(key, value);
40
+ if (options == null ? void 0 : options.EX) {
41
+ setTimeout(() => {
42
+ this.client.delete(key);
43
+ }, options.EX / 1e3);
44
+ }
45
+ }
46
+ del(key) {
47
+ this.client.delete(key);
48
+ }
49
+ clear() {
50
+ this.client.clear();
51
+ }
52
+ async DBSIZE() {
53
+ return Promise.resolve(this.client.size);
54
+ }
55
+ // This is just for testing
56
+ on(event, callback) {
57
+ if (event === "connect") {
58
+ callback("connect");
59
+ }
60
+ return this;
61
+ }
62
+ connect() {
63
+ return Promise.resolve(this);
64
+ }
65
+ };
66
+ var createLocalMemoryClient = () => {
67
+ return new LocalStorage();
68
+ };
69
+
70
+ // src/persistor.ts
29
71
  var REDIS_HOST = process.env.REDIS_HOST || "127.0.0.1";
30
72
  var REDIS_PORT = process.env.REDIS_PORT || 6379;
31
73
  var REDIS_URL = `redis://${REDIS_HOST}:${REDIS_PORT}`;
74
+ var CACHE_CLIENT = import_redis.createClient;
75
+ if (process.env.JEST_WORKER_ID) {
76
+ CACHE_CLIENT = createLocalMemoryClient;
77
+ }
32
78
  var Persistor = class {
33
- client;
79
+ client = null;
34
80
  status = "disconnected";
35
- constructor() {
81
+ constructor(isLocalPersistor) {
82
+ if (isLocalPersistor) {
83
+ CACHE_CLIENT = createLocalMemoryClient;
84
+ }
36
85
  this.connect();
37
86
  }
38
87
  async connect() {
39
88
  try {
40
- this.client = await (0, import_redis.createClient)({ url: REDIS_URL });
89
+ this.client = CACHE_CLIENT({ url: REDIS_URL });
41
90
  this.client.on("error", (err) => {
42
91
  console.error(`\u274C REDIS | Client Error | ${REDIS_URL}`, err);
43
92
  this.status = "disconnected";
@@ -49,7 +98,7 @@ var Persistor = class {
49
98
  return;
50
99
  }
51
100
  this.client.on("connect", () => {
52
- console.info(`\u{1F4E6} REDIS | Connection Ready | ${REDIS_URL}`);
101
+ console.log(`\u{1F4E6} REDIS | Connection Ready | ${REDIS_URL}`);
53
102
  this.status = "connected";
54
103
  resolve(true);
55
104
  });
@@ -80,15 +129,20 @@ var Persistor = class {
80
129
  throw error;
81
130
  }
82
131
  }
132
+ createOptions(ttl) {
133
+ if (ttl !== null && ttl !== void 0) {
134
+ return { EX: ttl / 1e3 };
135
+ }
136
+ return {};
137
+ }
83
138
  async set(key, { value, timestamp, ttl }) {
84
139
  if (!this.client) {
85
140
  throw new Error("Client not initialized");
86
141
  }
87
142
  try {
88
143
  const serializedData = JSON.stringify({ value, ttl, timestamp });
89
- await this.client.set(key, serializedData, {
90
- EX: ttl / 1e3
91
- });
144
+ const options = this.createOptions(ttl);
145
+ await this.client.set(key, serializedData, options);
92
146
  } catch (error) {
93
147
  console.error(`Error setting data in redis: ${error}`);
94
148
  throw error;
@@ -106,7 +160,10 @@ var Persistor = class {
106
160
  }
107
161
  }
108
162
  };
109
- var persistor = new Persistor();
163
+ var createPersistor = (isLocalPersistor) => {
164
+ const persistor = new Persistor(isLocalPersistor);
165
+ return persistor;
166
+ };
110
167
 
111
168
  // src/promiseCache.ts
112
169
  var PromiseCache = class {
@@ -119,10 +176,12 @@ var PromiseCache = class {
119
176
  * @param ttlInSeconds Default cache TTL.
120
177
  * @param caseSensitive Set to true if you want to differentiate between keys with different casing.
121
178
  */
122
- constructor(ttlInSeconds, caseSensitive = false) {
123
- this.persistor = persistor;
179
+ constructor(ttlInSeconds, caseSensitive = false, isLocalPersistor = false) {
180
+ this.persistor = createPersistor(isLocalPersistor);
124
181
  this.caseSensitive = caseSensitive;
125
- this.ttl = ttlInSeconds * 1e3;
182
+ if (ttlInSeconds) {
183
+ this.ttl = ttlInSeconds * 1e3;
184
+ }
126
185
  }
127
186
  /**
128
187
  * Cache size.
@@ -146,6 +205,14 @@ var PromiseCache = class {
146
205
  ttl: effectiveTTL
147
206
  });
148
207
  }
208
+ /**
209
+ * Get a value from the cache.
210
+ * @param key Cache key.
211
+ */
212
+ async find(key) {
213
+ const result = await this.persistor.get(key);
214
+ return (result == null ? void 0 : result.value) ?? null;
215
+ }
149
216
  /**
150
217
  * A simple promise cache wrapper.
151
218
  * @param key Cache key.
@@ -177,5 +244,7 @@ var PromiseCache = class {
177
244
  };
178
245
  // Annotate the CommonJS export names for ESM import in node:
179
246
  0 && (module.exports = {
180
- PromiseCache
247
+ LocalStorage,
248
+ PromiseCache,
249
+ createLocalMemoryClient
181
250
  });
package/dist/index.mjs CHANGED
@@ -1,17 +1,64 @@
1
1
  // src/persistor.ts
2
2
  import { createClient } from "redis";
3
+
4
+ // src/localMemory.ts
5
+ var LocalStorage = class {
6
+ client = /* @__PURE__ */ new Map();
7
+ get(key) {
8
+ return this.client.get(key);
9
+ }
10
+ set(key, value, options) {
11
+ this.client.set(key, value);
12
+ if (options == null ? void 0 : options.EX) {
13
+ setTimeout(() => {
14
+ this.client.delete(key);
15
+ }, options.EX / 1e3);
16
+ }
17
+ }
18
+ del(key) {
19
+ this.client.delete(key);
20
+ }
21
+ clear() {
22
+ this.client.clear();
23
+ }
24
+ async DBSIZE() {
25
+ return Promise.resolve(this.client.size);
26
+ }
27
+ // This is just for testing
28
+ on(event, callback) {
29
+ if (event === "connect") {
30
+ callback("connect");
31
+ }
32
+ return this;
33
+ }
34
+ connect() {
35
+ return Promise.resolve(this);
36
+ }
37
+ };
38
+ var createLocalMemoryClient = () => {
39
+ return new LocalStorage();
40
+ };
41
+
42
+ // src/persistor.ts
3
43
  var REDIS_HOST = process.env.REDIS_HOST || "127.0.0.1";
4
44
  var REDIS_PORT = process.env.REDIS_PORT || 6379;
5
45
  var REDIS_URL = `redis://${REDIS_HOST}:${REDIS_PORT}`;
46
+ var CACHE_CLIENT = createClient;
47
+ if (process.env.JEST_WORKER_ID) {
48
+ CACHE_CLIENT = createLocalMemoryClient;
49
+ }
6
50
  var Persistor = class {
7
- client;
51
+ client = null;
8
52
  status = "disconnected";
9
- constructor() {
53
+ constructor(isLocalPersistor) {
54
+ if (isLocalPersistor) {
55
+ CACHE_CLIENT = createLocalMemoryClient;
56
+ }
10
57
  this.connect();
11
58
  }
12
59
  async connect() {
13
60
  try {
14
- this.client = await createClient({ url: REDIS_URL });
61
+ this.client = CACHE_CLIENT({ url: REDIS_URL });
15
62
  this.client.on("error", (err) => {
16
63
  console.error(`\u274C REDIS | Client Error | ${REDIS_URL}`, err);
17
64
  this.status = "disconnected";
@@ -23,7 +70,7 @@ var Persistor = class {
23
70
  return;
24
71
  }
25
72
  this.client.on("connect", () => {
26
- console.info(`\u{1F4E6} REDIS | Connection Ready | ${REDIS_URL}`);
73
+ console.log(`\u{1F4E6} REDIS | Connection Ready | ${REDIS_URL}`);
27
74
  this.status = "connected";
28
75
  resolve(true);
29
76
  });
@@ -54,15 +101,20 @@ var Persistor = class {
54
101
  throw error;
55
102
  }
56
103
  }
104
+ createOptions(ttl) {
105
+ if (ttl !== null && ttl !== void 0) {
106
+ return { EX: ttl / 1e3 };
107
+ }
108
+ return {};
109
+ }
57
110
  async set(key, { value, timestamp, ttl }) {
58
111
  if (!this.client) {
59
112
  throw new Error("Client not initialized");
60
113
  }
61
114
  try {
62
115
  const serializedData = JSON.stringify({ value, ttl, timestamp });
63
- await this.client.set(key, serializedData, {
64
- EX: ttl / 1e3
65
- });
116
+ const options = this.createOptions(ttl);
117
+ await this.client.set(key, serializedData, options);
66
118
  } catch (error) {
67
119
  console.error(`Error setting data in redis: ${error}`);
68
120
  throw error;
@@ -80,7 +132,10 @@ var Persistor = class {
80
132
  }
81
133
  }
82
134
  };
83
- var persistor = new Persistor();
135
+ var createPersistor = (isLocalPersistor) => {
136
+ const persistor = new Persistor(isLocalPersistor);
137
+ return persistor;
138
+ };
84
139
 
85
140
  // src/promiseCache.ts
86
141
  var PromiseCache = class {
@@ -93,10 +148,12 @@ var PromiseCache = class {
93
148
  * @param ttlInSeconds Default cache TTL.
94
149
  * @param caseSensitive Set to true if you want to differentiate between keys with different casing.
95
150
  */
96
- constructor(ttlInSeconds, caseSensitive = false) {
97
- this.persistor = persistor;
151
+ constructor(ttlInSeconds, caseSensitive = false, isLocalPersistor = false) {
152
+ this.persistor = createPersistor(isLocalPersistor);
98
153
  this.caseSensitive = caseSensitive;
99
- this.ttl = ttlInSeconds * 1e3;
154
+ if (ttlInSeconds) {
155
+ this.ttl = ttlInSeconds * 1e3;
156
+ }
100
157
  }
101
158
  /**
102
159
  * Cache size.
@@ -120,6 +177,14 @@ var PromiseCache = class {
120
177
  ttl: effectiveTTL
121
178
  });
122
179
  }
180
+ /**
181
+ * Get a value from the cache.
182
+ * @param key Cache key.
183
+ */
184
+ async find(key) {
185
+ const result = await this.persistor.get(key);
186
+ return (result == null ? void 0 : result.value) ?? null;
187
+ }
123
188
  /**
124
189
  * A simple promise cache wrapper.
125
190
  * @param key Cache key.
@@ -150,5 +215,7 @@ var PromiseCache = class {
150
215
  }
151
216
  };
152
217
  export {
153
- PromiseCache
218
+ LocalStorage,
219
+ PromiseCache,
220
+ createLocalMemoryClient
154
221
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sebspark/promise-cache",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "license": "Apache-2.0",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",