Files
dmenu-api/src/modules/utils/cache.service.ts
T
2025-11-09 11:25:26 +03:30

150 lines
4.7 KiB
TypeScript
Executable File

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);
async onModuleInit() {
this.logger.log('Pinging Redis to check connection...');
try {
// 3. Try to set and get a test key
await this.cacheManager.set('ping', 'pong', 10); // 10-second TTL
const result = await this.cacheManager.get('ping');
if (result === 'pong') {
this.logger.log('✅ Redis connection successful (set/get test passed).');
} else {
this.logger.error(`❌ Redis connection test failed. Expected 'pong', got '${result}'.`);
}
// 4. Clean up the test key
await this.cacheManager.del('ping');
} catch (error) {
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) {
return await this.cacheManager.get<T>(key);
}
async set(key: string, value: string, ttl: number = 160) {
await this.cacheManager.set(key, value, ttl * 1000);
}
async del(key: string) {
await this.cacheManager.del(key);
}
async getTtl(key: string) {
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;
// }
// }
// }