zimovid

Cache decorator

Mar 10th, 2021
371
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { InternalServerErrorException } from '@nestjs/common';
  2.  
  3. export const Cacheable = (options: {cachePrefix: string, platform: string, ttl?: undefined}) => {
  4.  return (target: any, methodName: string, descriptor: TypedPropertyDescriptor<any>): void => {
  5.    const className = target.constructor.name;
  6.    const original = descriptor.value;
  7.    const { cachePrefix, ttl } = options;
  8.  
  9.    descriptor.value = new Proxy(original, {
  10.      apply: async (target: TargetInterFace<any>, service: ServiceInterface<any>, args: ArgsInterFace) => {
  11.        const { cacheManager, containerService } = service;
  12.        const platform = containerService.get('platformSlug')
  13.        if(!platform) {
  14.          return original
  15.        }
  16.  
  17.        if (!cacheManager) {
  18.          const message = `Target Class "${className}" should inject CACHE_MANAGER`
  19.  
  20.          throw new InternalServerErrorException(message);
  21.        }
  22.  
  23.        const cacheKey = `${cachePrefix}_${platform}`
  24.        const value = await cacheManager.get(cacheKey);
  25.        if (value) {
  26.          return value;
  27.        }
  28.  
  29.        const result = await target.apply(service, args);
  30.        await cacheManager.set(cacheKey, result, ttl);
  31.  
  32.        return result;
  33.      },
  34.    });
  35.  };
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment