(options = {})
| 204 | }; |
| 205 | |
| 206 | /** |
| 207 | * Generate key to save cache. |
| 208 | * @param {Object} [request] HTTP request argument to the middleware function passed by express. |
| 209 | * @returns {string} cache key. |
| 210 | */ |
| 211 | const generateCacheKey = (request) => { |
| 212 | return "cache:" + request.method + ":" + request.originalUrl; |
| 213 | }; |
| 214 | |
| 215 | /** |
| 216 | * Invalidate the cache for given keys |
| 217 | * @param {Object} [options] |
| 218 | * @param {Object} [options.invalidationKeys] Array of invalidation keys used in cache middleware. |
| 219 | * @returns {function} middleware function to help cache api response. |
| 220 | */ |
| 221 | const invalidateCache = (options = {}) => { |
| 222 | const keys = options.invalidationKeys; |
| 223 | |
| 224 | if (!Array.isArray(keys)) { |
| 225 | throw new Error("Invalidation keys must be an array"); |
| 226 | } |
| 227 | |
| 228 | return async (req, res, next) => { |
| 229 | res.on("finish", () => { |
| 230 | if (res.statusCode < 200 || res.statusCode >= 300) { |
| 231 | return; |
| 232 | } |
| 233 | try { |
| 234 | for (const key of keys) { |
| 235 | const cachedKeysSet = cachedKeys.getCachedKeys(key); |
no outgoing calls
no test coverage detected