From 9bb93f3fe5ad7a9c182b8cb81014ca0d0342cb20 Mon Sep 17 00:00:00 2001 From: domingo1021 Date: Sun, 30 Jun 2024 15:46:13 +0800 Subject: [PATCH] refactor: add cacheError decorator to catch cache error (#9) --- src/cores/decorators/cacheError.decorator.ts | 22 ++++++++++++++++++++ src/modules/cache/cache.service.ts | 4 ++++ 2 files changed, 26 insertions(+) create mode 100644 src/cores/decorators/cacheError.decorator.ts diff --git a/src/cores/decorators/cacheError.decorator.ts b/src/cores/decorators/cacheError.decorator.ts new file mode 100644 index 0000000..0f2c77a --- /dev/null +++ b/src/cores/decorators/cacheError.decorator.ts @@ -0,0 +1,22 @@ +/** + * Loose the cache dependency by wrapping the cache errors, if cache malfunction, the application will still work. + * + * @returns {Promise} + */ +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; + }; +}; diff --git a/src/modules/cache/cache.service.ts b/src/modules/cache/cache.service.ts index 6a232fc..a4606b7 100644 --- a/src/modules/cache/cache.service.ts +++ b/src/modules/cache/cache.service.ts @@ -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) {} @@ -13,6 +15,7 @@ export class CacheService implements OnModuleDestroy { * @param {string} key - The key of the value to retrieve. * @returns {Promise} The cached value, or null if the value is not in the cache. */ + @WrapCacheErrors() async get(key: string): Promise { const cachedValue = await this.cacheManager.get(key); if (!cachedValue) return null; @@ -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} */ + @WrapCacheErrors() async set(key: string, value: any, ttl: number = -1): Promise { if (ttl === -1) { const now = new Date();