Browse Source

fix:Adapting keyv store

pull/4270/merge^2
HarukaKishida 2 months ago
parent
commit
b35a29f597
  1. 18
      apps/api/src/app/redis-cache/redis-cache.module.ts
  2. 26
      apps/api/src/app/redis-cache/redis-cache.service.ts

18
apps/api/src/app/redis-cache/redis-cache.module.ts

@ -1,17 +1,16 @@
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module';
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { createKeyv } from '@keyv/redis';
import KeyvRedis, { Keyv } from '@keyv/redis';
import { CacheModule } from '@nestjs/cache-manager';
import { Module } from '@nestjs/common';
import type { RedisClientOptions } from 'redis';
import { RedisCacheService } from './redis-cache.service';
@Module({
exports: [RedisCacheService],
imports: [
CacheModule.registerAsync<RedisClientOptions>({
CacheModule.registerAsync<Keyv>({
imports: [ConfigurationModule],
inject: [ConfigurationService],
useFactory: async (configurationService: ConfigurationService) => {
@ -20,13 +19,14 @@ import { RedisCacheService } from './redis-cache.service';
);
return {
store: [
createKeyv(
store: new Keyv({
store: new KeyvRedis(
`redis://${redisPassword ? `:${redisPassword}` : ''}@${configurationService.get('REDIS_HOST')}:${configurationService.get('REDIS_PORT')}/${configurationService.get('REDIS_DB')}`
)
],
ttl: configurationService.get('CACHE_TTL')
};
),
ttl: configurationService.get('CACHE_TTL'),
useKeyPrefix: false
})
} as Keyv;
}
}),
ConfigurationModule

26
apps/api/src/app/redis-cache/redis-cache.service.ts

@ -19,13 +19,17 @@ export class RedisCacheService {
}
public async getKeys(aPrefix?: string): Promise<string[]> {
let prefix = aPrefix;
if (prefix) {
prefix = `${prefix}*`;
}
return this.cache.get(prefix);
const prefix = aPrefix;
const keyList = [];
this.cache.stores[0].iterator((key) => {
if (prefix && key.startsWith(prefix)) {
keyList.push(key);
} else if (!prefix) {
keyList.push(key);
}
});
return keyList;
}
public getPortfolioSnapshotKey({
@ -54,8 +58,9 @@ export class RedisCacheService {
public async isHealthy() {
try {
const client = this.cache.stores[0];
const isHealthy = await Promise.race([
this.cache,
client.ttl,
new Promise((_, reject) =>
setTimeout(
() => reject(new Error('Redis health check timeout')),
@ -82,10 +87,7 @@ export class RedisCacheService {
const keys = await this.getKeys(
`${this.getPortfolioSnapshotKey({ userId })}`
);
for (const key of keys) {
await this.remove(key);
}
this.cache.mdel(keys);
}
public async reset() {

Loading…
Cancel
Save