cache
This commit is contained in:
Generated
+78
-11
@@ -40,6 +40,7 @@
|
||||
"axios": "^1.13.1",
|
||||
"bullmq": "^5.65.1",
|
||||
"cache-manager": "^7.2.4",
|
||||
"cacheable": "^2.3.1",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.2",
|
||||
"dayjs": "^1.11.19",
|
||||
@@ -1934,13 +1935,26 @@
|
||||
"url": "https://github.com/sponsors/Borewit"
|
||||
}
|
||||
},
|
||||
"node_modules/@cacheable/utils": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.1.0.tgz",
|
||||
"integrity": "sha512-ZdxfOiaarMqMj+H7qwlt5EBKWaeGihSYVHdQv5lUsbn8MJJOTW82OIwirQ39U5tMZkNvy3bQE+ryzC+xTAb9/g==",
|
||||
"node_modules/@cacheable/memory": {
|
||||
"version": "2.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.0.6.tgz",
|
||||
"integrity": "sha512-7e8SScMocHxcAb8YhtkbMhGG+EKLRIficb1F5sjvhSYsWTZGxvg4KIDp8kgxnV2PUJ3ddPe6J9QESjKvBWRDkg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"keyv": "^5.5.3"
|
||||
"@cacheable/utils": "^2.3.2",
|
||||
"@keyv/bigmap": "^1.3.0",
|
||||
"hookified": "^1.13.0",
|
||||
"keyv": "^5.5.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@cacheable/utils": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.3.2.tgz",
|
||||
"integrity": "sha512-8kGE2P+HjfY8FglaOiW+y8qxcaQAfAhVML+i66XJR3YX5FtyDqn6Txctr3K2FrbxLKixRRYYBWMbuGciOhYNDg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"hashery": "^1.2.0",
|
||||
"keyv": "^5.5.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@colors/colors": {
|
||||
@@ -4040,6 +4054,22 @@
|
||||
"url": "https://opencollective.com/js-sdsl"
|
||||
}
|
||||
},
|
||||
"node_modules/@keyv/bigmap": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.0.tgz",
|
||||
"integrity": "sha512-KT01GjzV6AQD5+IYrcpoYLkCu1Jod3nau1Z7EsEuViO3TZGRacSbO9MfHmbJ1WaOXFtWLxPVj169cn2WNKPkIg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"hashery": "^1.2.0",
|
||||
"hookified": "^1.13.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"keyv": "^5.5.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@keyv/redis": {
|
||||
"version": "5.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@keyv/redis/-/redis-5.1.3.tgz",
|
||||
@@ -8018,6 +8048,19 @@
|
||||
"keyv": "^5.5.3"
|
||||
}
|
||||
},
|
||||
"node_modules/cacheable": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.3.1.tgz",
|
||||
"integrity": "sha512-yr+FSHWn1ZUou5LkULX/S+jhfgfnLbuKQjE40tyEd4fxGZVMbBL5ifno0J0OauykS8UiCSgHi+DV/YD+rjFxFg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@cacheable/memory": "^2.0.6",
|
||||
"@cacheable/utils": "^2.3.2",
|
||||
"hookified": "^1.14.0",
|
||||
"keyv": "^5.5.5",
|
||||
"qified": "^0.5.3"
|
||||
}
|
||||
},
|
||||
"node_modules/call-bind": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.8.tgz",
|
||||
@@ -10689,6 +10732,18 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/hashery": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/hashery/-/hashery-1.3.0.tgz",
|
||||
"integrity": "sha512-fWltioiy5zsSAs9ouEnvhsVJeAXRybGCNNv0lvzpzNOSDbULXRy7ivFWwCCv4I5Am6kSo75hmbsCduOoc2/K4w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"hookified": "^1.13.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/hasown": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
|
||||
@@ -10702,9 +10757,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/hookified": {
|
||||
"version": "1.12.2",
|
||||
"resolved": "https://registry.npmjs.org/hookified/-/hookified-1.12.2.tgz",
|
||||
"integrity": "sha512-aokUX1VdTpI0DUsndvW+OiwmBpKCu/NgRsSSkuSY0zq8PY6Q6a+lmOfAFDXAAOtBqJELvcWY9L1EVtzjbQcMdg==",
|
||||
"version": "1.14.0",
|
||||
"resolved": "https://registry.npmjs.org/hookified/-/hookified-1.14.0.tgz",
|
||||
"integrity": "sha512-pi1ynXIMFx/uIIwpWJ/5CEtOHLGtnUB0WhGeeYT+fKcQ+WCQbm3/rrkAXnpfph++PgepNqPdTC2WTj8A6k6zoQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/html-entities": {
|
||||
@@ -12201,9 +12256,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/keyv": {
|
||||
"version": "5.5.3",
|
||||
"resolved": "https://registry.npmjs.org/keyv/-/keyv-5.5.3.tgz",
|
||||
"integrity": "sha512-h0Un1ieD+HUrzBH6dJXhod3ifSghk5Hw/2Y4/KHBziPlZecrFyE9YOTPU6eOs0V9pYl8gOs86fkr/KN8lUX39A==",
|
||||
"version": "5.5.5",
|
||||
"resolved": "https://registry.npmjs.org/keyv/-/keyv-5.5.5.tgz",
|
||||
"integrity": "sha512-FA5LmZVF1VziNc0bIdCSA1IoSVnDCqE8HJIZZv2/W8YmoAM50+tnUgJR/gQZwEeIMleuIOnRnHA/UaZRNeV4iQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
@@ -13901,6 +13956,18 @@
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/qified": {
|
||||
"version": "0.5.3",
|
||||
"resolved": "https://registry.npmjs.org/qified/-/qified-0.5.3.tgz",
|
||||
"integrity": "sha512-kXuQdQTB6oN3KhI6V4acnBSZx8D2I4xzZvn9+wFLLFCoBNQY/sFnCW6c43OL7pOQ2HvGV4lnWIXNmgfp7cTWhQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"hookified": "^1.13.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.14.0",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"axios": "^1.13.1",
|
||||
"bullmq": "^5.65.1",
|
||||
"cache-manager": "^7.2.4",
|
||||
"cacheable": "^2.3.1",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.2",
|
||||
"dayjs": "^1.11.19",
|
||||
|
||||
@@ -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