(options = {})
| 143 | |
| 144 | return { getCachedKeys, addCachedKey, removeModelKey, removeCachedKey, clear }; |
| 145 | }; |
| 146 | |
| 147 | // Initialize cache pool. |
| 148 | const pool = cachePool(); |
| 149 | |
| 150 | const 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 | */ |
| 160 | const 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 | } |
no test coverage detected