cache
This commit is contained in:
@@ -24,10 +24,13 @@ import { PagerModule } from './modules/pager/pager.module';
|
||||
import { ContactModule } from './modules/contact/contact.module';
|
||||
import { InventoryModule } from './modules/inventory/inventory.module';
|
||||
import { IconsModule } from './modules/icons/icons.module';
|
||||
import { CacheModule } from '@nestjs/cache-manager';
|
||||
import { cacheConfig } from './config/cache.config';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true, cache: true }),
|
||||
CacheModule.registerAsync(cacheConfig()),
|
||||
MikroOrmModule.forRootAsync(dataBaseConfig),
|
||||
UserModule,
|
||||
UtilsModule,
|
||||
|
||||
+13
-15
@@ -1,29 +1,27 @@
|
||||
import { Keyv } from 'keyv';
|
||||
import KeyvRedis from '@keyv/redis';
|
||||
import Keyv from 'keyv';
|
||||
import type { CacheModuleAsyncOptions } from '@nestjs/cache-manager';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Logger } from '@nestjs/common'; // 1. Import Logger
|
||||
import { CacheableMemory } from 'cacheable';
|
||||
|
||||
export function cacheConfig(): CacheModuleAsyncOptions {
|
||||
return {
|
||||
isGlobal: true,
|
||||
inject: [ConfigService],
|
||||
useFactory: (configService: ConfigService) => {
|
||||
useFactory: async (configService: ConfigService) => {
|
||||
const redisUri = configService.get('REDIS_URI');
|
||||
const namespace = configService.get('CACHE_NAMESPACE', 'app-cache');
|
||||
const ttl = configService.get<number>('CACHE_TTL', 3600);
|
||||
const namespace = configService.get<string>('CACHE_NAMESPACE', 'app-cache');
|
||||
|
||||
const redisUri = configService.getOrThrow<string>('REDIS_URI');
|
||||
|
||||
const store = new Keyv({
|
||||
store: new KeyvRedis(redisUri),
|
||||
namespace,
|
||||
});
|
||||
|
||||
return {
|
||||
store,
|
||||
ttl, // cache-manager handles TTL
|
||||
stores: [
|
||||
new Keyv({
|
||||
store: new CacheableMemory({ ttl: ttl*1000, lruSize: 5000 }),
|
||||
namespace: namespace
|
||||
}),
|
||||
new KeyvRedis(redisUri, { namespace: namespace }),
|
||||
],
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,12 +4,17 @@ import { Inject, Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
@Injectable()
|
||||
export class CacheService implements OnModuleInit {
|
||||
private readonly logger = new Logger(CacheService.name);
|
||||
|
||||
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
|
||||
|
||||
async onModuleInit() {
|
||||
;
|
||||
this.logger.log(`Active Cache Store: ${JSON.stringify(this.cacheManager as any)}`);
|
||||
|
||||
// Should log 'Keyv' or 'KeyvRedis'. If it says 'Memory', the config is still wrong.
|
||||
this.logger.log('Pinging Redis to check connection...');
|
||||
try {
|
||||
// 3. Try to set and get a test key
|
||||
// Use the wrapper to keep TTL units consistent (seconds -> ms)
|
||||
await this.set('ping', 'pong', 10); // 10-second TTL
|
||||
await this.set('ping', 'pong', 10); // TTL in seconds
|
||||
const result = await this.get('ping');
|
||||
|
||||
if (result === 'pong') {
|
||||
@@ -18,131 +23,30 @@ export class CacheService implements OnModuleInit {
|
||||
this.logger.error(`❌ Redis connection test failed. Expected 'pong', got '${result}'.`);
|
||||
}
|
||||
|
||||
// 4. Clean up the test key
|
||||
await this.cacheManager.del('ping');
|
||||
} catch (error) {
|
||||
await this.del('ping');
|
||||
} catch (error: any) {
|
||||
this.logger.error('❌ Failed to connect to Redis during ping test:', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) { }
|
||||
|
||||
async get<T>(key: string) {
|
||||
/** Get value from cache */
|
||||
async get<T>(key: string): Promise<T | undefined> {
|
||||
return await this.cacheManager.get<T>(key);
|
||||
}
|
||||
|
||||
async set(key: string, value: string, ttl: number = 160) {
|
||||
await this.cacheManager.set(key, value, ttl * 1000);
|
||||
/** Set value in cache with TTL in seconds */
|
||||
async set(key: string, value: any, ttlSeconds: number) {
|
||||
// cache-manager expects TTL in seconds
|
||||
await this.cacheManager.set(key, value, ttlSeconds * 1000);
|
||||
}
|
||||
|
||||
/** Delete a key from cache */
|
||||
async del(key: string) {
|
||||
await this.cacheManager.del(key);
|
||||
}
|
||||
|
||||
async getTtl(key: string) {
|
||||
/** Get remaining TTL in seconds */
|
||||
async getTtl(key: string): Promise<number | undefined> {
|
||||
return await this.cacheManager.ttl(key);
|
||||
}
|
||||
}
|
||||
|
||||
// // src/modules/cache/cache.service.ts
|
||||
// import { CACHE_MANAGER, Cache } from '@nestjs/cache-manager';
|
||||
// import { Inject, Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
|
||||
// @Injectable()
|
||||
// export class CacheService implements OnModuleInit {
|
||||
// private readonly logger = new Logger(CacheService.name);
|
||||
|
||||
// constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
|
||||
|
||||
// /**
|
||||
// * On-init lifecycle hook to test the cache connection.
|
||||
// */
|
||||
// async onModuleInit() {
|
||||
// this.logger.log('Pinging Redis to check connection...');
|
||||
// const testKey = 'ping';
|
||||
// const testValue = 'pong';
|
||||
|
||||
// try {
|
||||
// // 1. Set test key with a 10-second TTL
|
||||
// // Note: We use the wrapper to ensure consistent TTL logic (seconds -> ms)
|
||||
// await this.set(testKey, testValue, 10);
|
||||
|
||||
// // 2. Get test key
|
||||
// const result = await this.get(testKey);
|
||||
|
||||
// if (result === testValue) {
|
||||
// this.logger.log('✅ Redis connection successful (set/get test passed).');
|
||||
// } else {
|
||||
// this.logger.error(
|
||||
// `❌ Redis connection test failed. Expected '${testValue}', got '${result}'.`,
|
||||
// );
|
||||
// }
|
||||
|
||||
// // 3. Clean up the test key
|
||||
// await this.del(testKey);
|
||||
// } catch (error) {
|
||||
// this.logger.error(
|
||||
// '❌ Failed to connect to Redis during ping test:',
|
||||
// error.message,
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Gets a value from the cache.
|
||||
// * @param key The cache key.
|
||||
// * @returns The cached value or undefined.
|
||||
// */
|
||||
// async get<T>(key: string): Promise<T | undefined> {
|
||||
// try {
|
||||
// return await this.cacheManager.get<T>(key);
|
||||
// } catch (error) {
|
||||
// this.logger.error(`Error getting from cache (key: ${key}):`, error.message);
|
||||
// return undefined; // Fail gracefully
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Sets a value in the cache.
|
||||
// * @param key The cache key.
|
||||
// * @param value The value to store (can be any serializable type).
|
||||
// * @param ttlInSeconds The time-to-live in **seconds**.
|
||||
// */
|
||||
// async set(key: string, value: unknown, ttlInSeconds: number = 160): Promise<void> {
|
||||
// try {
|
||||
// // Convert seconds to milliseconds for cache-manager
|
||||
// await this.cacheManager.set(key, value, ttlInSeconds * 1000);
|
||||
// } catch (error) {
|
||||
// this.logger.error(`Error setting cache (key: ${key}):`, error.message);
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Deletes a value from the cache.
|
||||
// * @param key The cache key to delete.
|
||||
// */
|
||||
// async del(key: string): Promise<void> {
|
||||
// try {
|
||||
// await this.cacheManager.del(key);
|
||||
// } catch (error)
|
||||
// {
|
||||
// this.logger.error(`Error deleting from cache (key: ${key}):`, error.message);
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Gets the remaining TTL for a key in seconds.
|
||||
// * Note: This implementation is specific to redis-store.
|
||||
// * @param key The cache key.
|
||||
// * @returns The remaining TTL in seconds, or -1 (no expiry) / -2 (key doesn't exist).
|
||||
// */
|
||||
// async getTtl(key: string): Promise<number | undefined> {
|
||||
// try {
|
||||
// // The `ttl` method from cache-manager-redis-store returns TTL in seconds
|
||||
// return await this.cacheManager.ttl(key);
|
||||
// } catch (error) {
|
||||
// this.logger.error(`Error getting TTL (key: ${key}):`, error.message);
|
||||
// return undefined;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CacheService } from './cache.service';
|
||||
import { SmsService } from './sms.service';
|
||||
import { CacheModule } from '@nestjs/cache-manager';
|
||||
import { cacheConfig } from '../../config/cache.config';
|
||||
|
||||
|
||||
@Module({
|
||||
imports: [CacheModule.registerAsync(cacheConfig())],
|
||||
imports: [],
|
||||
controllers: [],
|
||||
providers: [CacheService, SmsService],
|
||||
exports: [CacheService, SmsService],
|
||||
|
||||
Reference in New Issue
Block a user