MCPcopy Create free account
hub / github.com/RealDevSquad/website-backend / cachePool

Function cachePool

utils/cache.js:10–73  ·  view source on GitHub ↗
(opt = { maximumSize: CACHE_SIZE_MB })

Source from the content-addressed store, hash-verified

8 * @param {Object} [opt] options for cache pool
9 * @param {number} opt.maximumSize Maximum size of the cache pool in Megabytes (MB)
10 */
11const cachePool = (opt = { maximumSize: CACHE_SIZE_MB }) => {
12 const cacheStore = new Map();
13
14 let hits = 0;
15
16 /**
17 * Get an API Response from cacheStore.
18 * @param {string} key
19 * @returns {null | object}
20 */
21 const get = (key) => {
22 const cachedData = cacheStore.get(key);
23
24 if (!cachedData) {
25 return null;
26 }
27
28 const isCacheDataExpired = new Date().getTime() > cachedData.expiry;
29
30 // If data is expired remove it from store, time to get a fresh copy.
31 if (isCacheDataExpired) {
32 evict(key);
33 return null;
34 }
35
36 hits += 1;
37 try {
38 return JSON.parse(cachedData.response);
39 } catch (err) {
40 logger.error(`Error while parsing cachedData.response ${err}`);
41 throw err;
42 }
43 };
44
45 /**
46 * Remove an API Response from cacheStore.
47 * @param {string} key
48 * @returns {boolean}
49 */
50 const evict = (key) => {
51 return cacheStore.delete(key);
52 };
53
54 /**
55 * Add API response to cacheStore.
56 * @param {string} key
57 * @param {Object} value Value to be stored inside the cache.
58 * @param {number} value.priority Priority of the api
59 * @param {string} value.response Response from controller
60 * @param {number} value.expiry Expiry time of api
61 * @param {number} value.size Size of api response in byte
62 * @returns {number} : statusCode
63 */
64 const set = async (key, value) => {
65 try {
66 cacheStore.set(key, value);
67 return true;

Callers 1

cache.jsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected