Skip to content

Instantly share code, notes, and snippets.

@sunnyy02
Created April 2, 2022 04:59
Show Gist options
  • Save sunnyy02/5f6754f3a51311191320e9d544aac7a3 to your computer and use it in GitHub Desktop.
Save sunnyy02/5f6754f3a51311191320e9d544aac7a3 to your computer and use it in GitHub Desktop.
import { CACHE_MANAGER, Inject } from '@nestjs/common';
export const cacheManagerDecorator = (ttl = 10) => {
const injectCache = Inject(CACHE_MANAGER);
return function (
target: any,
_propertyName: string,
descriptor: PropertyDescriptor,
) {
injectCache(target, 'cache');
const decoratedMethod = descriptor.value;
const cacheKey = `${target.constructor.name}-${decoratedMethod?.name}`;
descriptor.value = async function () {
const cachedData = await this.cache.get(cacheKey);
if (cachedData) {
console.log('cachedData:', cachedData);
return cachedData;
}
const response = await decoratedMethod.apply(this, arguments);
this.cache.set(cacheKey, response, { ttl: ttl });
console.log('response:', response);
return response;
};
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment