Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { InternalServerErrorException } from '@nestjs/common';
- export const Cacheable = (options: {cachePrefix: string, platform: string, ttl?: undefined}) => {
- return (target: any, methodName: string, descriptor: TypedPropertyDescriptor<any>): void => {
- const className = target.constructor.name;
- const original = descriptor.value;
- const { cachePrefix, ttl } = options;
- descriptor.value = new Proxy(original, {
- apply: async (target: TargetInterFace<any>, service: ServiceInterface<any>, args: ArgsInterFace) => {
- const { cacheManager, containerService } = service;
- const platform = containerService.get('platformSlug')
- if(!platform) {
- return original
- }
- if (!cacheManager) {
- const message = `Target Class "${className}" should inject CACHE_MANAGER`
- throw new InternalServerErrorException(message);
- }
- const cacheKey = `${cachePrefix}_${platform}`
- const value = await cacheManager.get(cacheKey);
- if (value) {
- return value;
- }
- const result = await target.apply(service, args);
- await cacheManager.set(cacheKey, result, ttl);
- return result;
- },
- });
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment