Skip to content
This repository has been archived by the owner on Jan 24, 2024. It is now read-only.

Commit

Permalink
fix: init cache earlier to prevent infinite loop (#252)
Browse files Browse the repository at this point in the history
  • Loading branch information
xdrdak authored Apr 25, 2022
1 parent d7eca46 commit a2f1152
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions src/cache/cache-on-interval.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,22 +69,34 @@ export class CacheOnIntervalService implements OnModuleInit, OnModuleDestroy {
const cacheManager = this.cacheManager;

// Augment the method to be cached with caching mechanism
instance[methodName] = async function (...args: any[]) {
instance[methodName] = async function () {
const cachedValue = await cacheManager.get(cacheKey);

if (cachedValue) {
return cachedValue;
} else {
try {
const liveData = await methodRef.apply(instance, args);
await cacheManager.set(cacheKey, liveData, { ttl });
return liveData;
} catch (e) {
logger.error(`@CacheOnInterval error for ${instance.constructor.name}#${methodName}`, e);
}
logger.warn(
`@CacheOnInterval has no cache primed for ${instance.constructor.name}#${methodName}. Please wait for a few seconds as the cache is primed.`,
);
}
};

let liveData = methodRef.apply(instance);
// Duck typing shennanigans
if (!liveData.then) {
liveData = new Promise(liveData);
}
liveData
.then(d => {
return cacheManager.set(cacheKey, d, { ttl });
})
.then(() => {
logger.log(`Cache ready for for ${instance.constructor.name}#${methodName}`);
})
.catch(e => {
logger.error(`@CacheOnInterval error init for ${instance.constructor.name}#${methodName}`, e);
});

// Save the interval
const interval = setInterval(async () => {
try {
Expand Down

0 comments on commit a2f1152

Please sign in to comment.