All files express-cache.ts

21.56% Statements 22/102
24.56% Branches 14/57
5% Functions 1/20
22.44% Lines 22/98

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 2791x       1x 1x                                                                                                                                                                         1x             4x     4x     4x         4x 1x     3x 1x     2x 1x     1x 1x 1x 1x 1x 1x   1x       1x       1x                                                                                                                                                                                                                                                                                              
import tagGenerator from 'etag';
import { Request, Response, NextFunction } from 'express';
 
import { REDIS_PACKAGE } from './constans';
import { RedisClient, RedisClientWrapper } from './redis-client-wrapper';
import { responseEndOverrider } from './response-end-overrider';
 
export interface ExpressCacheErrorHandler {
  (error: Error, req: Request, res: Response, next: NextFunction): void;
}
 
export interface ExpressCacheOptions {
  /**
   * saved cache name on redis
   * format name: [key-prefix]:[tag-prefix][tag]
   * Default is "expch"
   */
  keyPrefix?: string;
  /**
   * Time to live in second. Default ttl is 60 second or 1 hour
   */
  ttl?: number;
  /**
   * Redis Client
   */
  redis: {
    package: REDIS_PACKAGE;
    client: any;
  };
  /**
   * Header Cache Name on Request. Default is "if-none-match":
   */
  requestHeaderName?: string;
  /**
   * Header Cache Name on Response. Default is "etag"
   */
  responseHeaderName?: string;
  /**
   * Triggered function if read cache is error
   * Default function is throw error
   */
  readCacheErrHandler?: ExpressCacheErrorHandler;
  /**
   * Triggered function if store cache is error
   * Default function is throw error
   */
  storeCacheErrHandler?: ExpressCacheErrorHandler;
  /**
   * Triggered function if clear cache is error
   * Default function is throw error
   */
  clearCacheErrHandler?: ExpressCacheErrorHandler;
}
 
export interface ExpressCacheMiddlewareOptions {
  /**
   * tag prefix for cache name
   * Default: string from req.path
   */
  tagPrefix?: string | ((req: Request) => string);
  /**
   * validate whether data can be cached
   * By default the data will be saved if the http status code is 200-299
   */
  isCanSaveFn?: ExpressCacheValidateFunction;
}
 
export interface ExpressCacheClearOptions {
  /**
   * tag pattern for cache key
   * Default: string from req.path with asterix
   * Example: users-*
   */
  tagPattern?: string | string[] | ((req: Request) => string | string[]);
  /**
   * validate whether cache can be cleared
   * By default the data will be clear if the http status code is 200-299
   */
  isCanClearFn?: ExpressCacheValidateFunction;
}
 
interface DataCache {
  httpStatusCode: number;
  headers: any;
  body: any;
}
 
type ExpressCacheRequestHandler = (req: Request, res: Response, next: NextFunction) => Promise<void>;
type ExpressCacheValidateFunction = (httpStatusCode: number, res: Response, req: Request) => boolean;
 
export class ExpressCache {
  private keyPrefix: string;
  private tagPrefix: string;
  private ttl: number;
  private wrappedRedisClient: RedisClient;
  private requestHeaderName: string;
  private responseHeaderName: string;
  private readCacheErrHandler: ExpressCacheErrorHandler = (err) => {
    throw err;
  };
  private storeCacheErrHandler: ExpressCacheErrorHandler = (err) => {
    throw err;
  };
  private clearCacheErrHandler: ExpressCacheErrorHandler = (err) => {
    throw err;
  };
 
  constructor(opts: ExpressCacheOptions) {
    if (!opts.redis) {
      throw new Error('redis options is required');
    }
 
    if (!opts.redis.package) {
      throw new Error('redis package is required');
    }
 
    if (!opts.redis.client) {
      throw new Error('redis client is required');
    }
 
    this.wrappedRedisClient = new RedisClientWrapper(opts.redis.package, opts.redis.client).getWrapper();
    this.keyPrefix = opts.keyPrefix || 'express-cache:';
    this.ttl = opts.ttl || 60;
    this.requestHeaderName = opts.requestHeaderName || 'if-none-match';
    this.responseHeaderName = opts.responseHeaderName || 'etag';
    this.tagPrefix = '';
 
    Iif (opts.readCacheErrHandler && typeof opts.readCacheErrHandler === 'function') {
      this.readCacheErrHandler = opts.readCacheErrHandler;
    }
 
    Iif (opts.storeCacheErrHandler && typeof opts.storeCacheErrHandler === 'function') {
      this.storeCacheErrHandler = opts.storeCacheErrHandler;
    }
 
    Iif (opts.clearCacheErrHandler && typeof opts.clearCacheErrHandler === 'function') {
      this.clearCacheErrHandler = opts.clearCacheErrHandler;
    }
  }
 
  middleware(opts: ExpressCacheMiddlewareOptions): ExpressCacheRequestHandler {
    let isCanSaveFn: (httpStatusCode: number, res: Response, req: Request) => boolean = (httpStatusCode: number) =>
      httpStatusCode >= 200 && httpStatusCode <= 299;
 
    Iif (opts.isCanSaveFn && typeof opts.isCanSaveFn === 'function') {
      isCanSaveFn = opts.isCanSaveFn;
    }
 
    return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
      if (opts.tagPrefix && typeof opts.tagPrefix === 'string') {
        this.tagPrefix = opts.tagPrefix;
      } else if (opts.tagPrefix && typeof opts.tagPrefix === 'function') {
        this.tagPrefix = opts.tagPrefix(req);
      } else {
        const queryString = Object.keys(req.query).length > 0 ? JSON.stringify(req.query) : '';
        this.tagPrefix = req.originalUrl + queryString;
      }
 
      // response from cache
      try {
        const tag = req.header(this.requestHeaderName) as string;
        Iif (tag) {
          const key = this.getKey(tag);
          const dataCache = await this.getCache(key);
          Iif (dataCache) {
            res.status(dataCache.httpStatusCode).set(dataCache.headers).end(dataCache.body);
            return;
          }
        }
      } catch (err: Error | any) {
        await this.readCacheErrHandler(err, req, res, next);
        return;
      }
 
      // store response to cache
      const fn = async (resBody: string) => {
        const isAllowSaveCache = await isCanSaveFn(res.statusCode, res, req);
 
        Iif (!isAllowSaveCache) {
          return;
        }
 
        try {
          const tag = tagGenerator(resBody, { weak: false });
          res.header(this.responseHeaderName, tag);
 
          const data: DataCache = {
            httpStatusCode: res.statusCode,
            headers: res.getHeaders(),
            body: resBody,
          };
 
          const key = this.getKey(tag);
          await this.setCache(key, data);
        } catch (err: Error | any) {
          await this.storeCacheErrHandler(err, req, res, next);
        }
      };
 
      responseEndOverrider(res, fn);
      next();
    };
  }
 
  private getKey(tag: string): string {
    return this.keyPrefix + this.tagPrefix + tag;
  }
 
  private async getCache(key: string): Promise<DataCache | null> {
    const data = await this.wrappedRedisClient.get(key);
    Iif (!data) {
      return null;
    }
 
    const cache: DataCache = JSON.parse(data);
    return cache;
  }
 
  private async setCache(key: string, data: any): Promise<void> {
    await this.wrappedRedisClient.set(key, JSON.stringify(data), {
      EX: this.ttl,
    });
  }
 
  clear(opts: ExpressCacheClearOptions): ExpressCacheRequestHandler {
    const keyPatterns: string[] = [];
    let isCanClearFn: (httpStatusCode: number, res: Response, req: Request) => boolean = (httpStatusCode: number) =>
      httpStatusCode >= 200 && httpStatusCode <= 299;
 
    Iif (opts.isCanClearFn && typeof opts.isCanClearFn === 'function') {
      isCanClearFn = opts.isCanClearFn;
    }
 
    return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
      Iif (opts.tagPattern && typeof opts.tagPattern === 'function') {
        opts.tagPattern = await opts.tagPattern(req);
      }
 
      if (opts.tagPattern && typeof opts.tagPattern === 'string') {
        const keyPattern = this.keyPrefix + opts.tagPattern;
        keyPatterns.push(keyPattern);
      } else Iif (Array.isArray(opts.tagPattern) && opts.tagPattern.length > 0) {
        for (const tp of opts.tagPattern) {
          const keyPattern = this.keyPrefix + tp;
          keyPatterns.push(keyPattern);
        }
      }
 
      Iif (keyPatterns.length > 0) {
        const fn = async () => {
          const isCanClear = await isCanClearFn(res.statusCode, res, req);
 
          Iif (!isCanClear) {
            return;
          }
 
          try {
            const results = await Promise.all<Promise<string[]>[]>(
              keyPatterns.map<Promise<string[]>>((keyPattern) => this.wrappedRedisClient.keys(keyPattern)),
            );
 
            const keys: string[] = ([] as string[]).concat(...results);
 
            Iif (keys.length > 0) {
              await this.wrappedRedisClient.del(...keys);
            }
          } catch (err: Error | any) {
            await this.clearCacheErrHandler(err, req, res, next);
          }
        };
 
        responseEndOverrider(res, fn);
      }
 
      next();
    };
  }
}