يعد التخزين المؤقت تقنية أساسية لتحسين أداء تطبيقاتك وقابلية التوسع. في Nest.js، يمكن دمج التخزين المؤقت بسلاسة باستخدام مدير ذاكرة التخزين المؤقت المدمج. في هذه المقالة، سنستكشف كيفية إنشاء مصمم @Cacheable مخصص لتبسيط التخزين المؤقت في خدمات Nest.js أو وحدات التحكم الخاصة بك.
بينما يوفر Nest.js آليات تخزين مؤقت قوية خارج الصندوق، فإن تطبيق منطق التخزين المؤقت مباشرة ضمن أساليبك يمكن أن يؤدي إلى فوضى التعليمات البرمجية الخاصة بك. يلخص مصمم الديكور المخصص هذا المنطق، مما يجعل التعليمات البرمجية الخاصة بك أكثر وضوحًا وأكثر قابلية للصيانة.
لنبدأ بإنشاء مصمم @Cacheable الذي سنستخدمه لتخزين نتائج أساليبنا مؤقتًا.
import { Cache } from 'cache-manager'; export function Cacheable(cacheKey: string) { return function ( target: any, propertyName: string, descriptor: PropertyDescriptor, ) { const originalMethod = descriptor.value; descriptor.value = async function (...args: any[]) { const cache: Cache = this.cacheManager; if (!cache) { throw new Error( 'Cannot use Cacheable() decorator without injecting the cache manager.', ); } // Try to get cached data try { const cachedResult = await cache.get(cacheKey); if (cachedResult) { return cachedResult; } } catch (error) { console.error(`Cache get error for key: ${cacheKey}:`, error); } // Call the original method if cache miss const result = await originalMethod.apply(this, args); // Set the new result in cache try { await cache.set(cacheKey, result); } catch (error) { console.error(`Cache set error for key: ${cacheKey}:`, error); } return result; }; return descriptor; }; }
إليك كيفية تطبيق مصمم @Cacheable على طريقة في خدمتك:
import { Injectable } from '@nestjs/common'; import { Cacheable } from './cacheable.decorator'; const SETTING_CACHE_KEY = 'settings'; @Injectable() export class SettingsService { // Inject the cache manager constructor(private readonly cacheManager: Cache) {} /** * Retrieves settings from the cache if available, or loads them from the * repository and caches the result. * * @returns A promise that resolves to a `Settings` object. */ @Cacheable(SETTING_CACHE_KEY) async getSettings(): Promise{ return await this.findAll(); } // ... other methods like findAll() and buildTree() }
لاستخدام مدير ذاكرة التخزين المؤقت في تطبيقك، تحتاج إلى تسجيله في وحدتك:
import { Module } from '@nestjs/common'; import { CacheModule } from '@nestjs/cache-manager'; import { SettingsService } from './settings.service'; @Module({ imports: [ CacheModule.register({ isGlobal: true, ttl: 300, // Time to live in seconds max: 100, // Maximum number of items in cache }), ], providers: [SettingsService], }) export class AppModule {}
تأكد من إدخال مدير ذاكرة التخزين المؤقت في أي خدمة أو وحدة تحكم تستخدم مصمم الديكور @Cacheable:
import { Injectable } from '@nestjs/common'; import { Cache } from 'cache-manager'; @Injectable() export class SettingsService { constructor(private readonly cacheManager: Cache) {} // ... your methods }
من خلال إنشاء مصمم @Cacheable مخصص، يمكنك الحفاظ على أساليبك نظيفة والتركيز على المنطق الأساسي، وترك مخاوف التخزين المؤقت لمصمم الديكور. يعمل هذا الأسلوب على تحسين إمكانية قراءة التعليمات البرمجية وإمكانية صيانتها، مما يجعل تطبيق Nest.js الخاص بك أكثر كفاءة وقابلية للتطوير.
لا تتردد في ترك التعليقات أو الأسئلة أدناه. ترميز سعيد! ?
تنصل: جميع الموارد المقدمة هي جزئيًا من الإنترنت. إذا كان هناك أي انتهاك لحقوق الطبع والنشر الخاصة بك أو الحقوق والمصالح الأخرى، فيرجى توضيح الأسباب التفصيلية وتقديم دليل على حقوق الطبع والنشر أو الحقوق والمصالح ثم إرسالها إلى البريد الإلكتروني: [email protected]. سوف نتعامل مع الأمر لك في أقرب وقت ممكن.
Copyright© 2022 湘ICP备2022001581号-3