Skip to content

Commit

Permalink
refactor: add cacheError decorator to catch cache error (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
domingo1021 authored Jun 30, 2024
1 parent 0b3ee2f commit 9bb93f3
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/cores/decorators/cacheError.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Loose the cache dependency by wrapping the cache errors, if cache malfunction, the application will still work.
*
* @returns {Promise<any>}
*/
export const WrapCacheErrors = () => {
return (_target: any, _propertyKey: string, descriptor: PropertyDescriptor) => {
const originalMethod = descriptor.value;

descriptor.value = async function (...args: any[]) {
try {
const result = await originalMethod.apply(this, args);
return result;
} catch (err) {
console.error('Cache Error: ', err.message);
return null;
}
};

return descriptor;
};
};
4 changes: 4 additions & 0 deletions src/modules/cache/cache.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { Injectable, Inject, OnModuleDestroy } from '@nestjs/common';

import { Cache } from 'cache-manager';

import { WrapCacheErrors } from '#cores/decorators/cacheError.decorator';

@Injectable()
export class CacheService implements OnModuleDestroy {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
Expand All @@ -13,6 +15,7 @@ export class CacheService implements OnModuleDestroy {
* @param {string} key - The key of the value to retrieve.
* @returns {Promise<T | null>} The cached value, or null if the value is not in the cache.
*/
@WrapCacheErrors()
async get<T>(key: string): Promise<T | null> {
const cachedValue = await this.cacheManager.get<T>(key);
if (!cachedValue) return null;
Expand All @@ -26,6 +29,7 @@ export class CacheService implements OnModuleDestroy {
* @param ttl the time to live in seconds, default is until 4:00 AM next day
* @returns {Promise<void>}
*/
@WrapCacheErrors()
async set(key: string, value: any, ttl: number = -1): Promise<void> {
if (ttl === -1) {
const now = new Date();
Expand Down

0 comments on commit 9bb93f3

Please sign in to comment.