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

Function cacheResponse

utils/cache.js:145–189  ·  view source on GitHub ↗
(options = {})

Source from the content-addressed store, hash-verified

143
144 return { getCachedKeys, addCachedKey, removeModelKey, removeCachedKey, clear };
145};
146
147// Initialize cache pool.
148const pool = cachePool();
149
150const cachedKeys = cachedKeysStore();
151
152/**
153 * Caching middleware for API resposnes.
154 * @param {Object} [options] Options to handle individual api cache.
155 * @param {number} options.priority The priority of api in cache store.
156 * @param {number} options.expiry Cache expiry time of api in minutes.
157 * @param {number} options.invalidationKey key to be used while using the invalidateCache middleware.
158 * @returns {function} middleware function to help cache api response.
159 */
160const cacheResponse = (options = {}) => {
161 const priority = options.priority || 2;
162 const expiry = options.expiry || CACHE_EXPIRY_TIME_MIN;
163 const modelKey = options.invalidationKey;
164 return async (req, res, next) => {
165 try {
166 const key = generateCacheKey(req);
167 const cacheData = pool.get(key);
168 if (cacheData) {
169 res.send(cacheData);
170 } else {
171 /**
172 * As we do not have data in our cache we call the next middleware,
173 * intercept the response being sent from middleware and store it in cache.
174 * */
175 const oldSend = res.send;
176
177 res.send = (body) => {
178 if (res.statusCode < 200 || res.statusCode >= 300) {
179 res.send = oldSend;
180 return res.send(body);
181 }
182
183 const cacheValue = {
184 priority: priority,
185 response: body,
186 expiry: new Date().getTime() + minutesToMilliseconds(expiry),
187 size: Buffer.byteLength(body),
188 };
189 pool.set(key, cacheValue);
190 if (modelKey) {
191 cachedKeys.addCachedKey(modelKey, key);
192 }

Callers 2

tasks.jsFile · 0.85
cache.test.jsFile · 0.85

Calls 3

generateCacheKeyFunction · 0.85
minutesToMillisecondsFunction · 0.85
getMethod · 0.80

Tested by

no test coverage detected