Created
April 2, 2022 04:59
-
-
Save sunnyy02/5f6754f3a51311191320e9d544aac7a3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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