barkey/packages/backend/src/core/UserKeypairService.ts

45 lines
1.3 KiB
TypeScript
Raw Normal View History

import { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';
2023-04-14 04:50:05 +00:00
import * as Redis from 'ioredis';
2022-09-17 18:27:08 +00:00
import type { User } from '@/models/entities/User.js';
2022-09-20 20:33:11 +00:00
import type { UserKeypairsRepository } from '@/models/index.js';
import { RedisKVCache } from '@/misc/cache.js';
2022-09-17 18:27:08 +00:00
import type { UserKeypair } from '@/models/entities/UserKeypair.js';
import { DI } from '@/di-symbols.js';
import { bindThis } from '@/decorators.js';
2022-09-17 18:27:08 +00:00
@Injectable()
export class UserKeypairService implements OnApplicationShutdown {
private cache: RedisKVCache<UserKeypair>;
2022-09-17 18:27:08 +00:00
constructor(
@Inject(DI.redis)
private redisClient: Redis.Redis,
2022-09-17 18:27:08 +00:00
@Inject(DI.userKeypairsRepository)
private userKeypairsRepository: UserKeypairsRepository,
) {
this.cache = new RedisKVCache<UserKeypair>(this.redisClient, 'userKeypair', {
lifetime: 1000 * 60 * 60 * 24, // 24h
memoryCacheLifetime: Infinity,
fetcher: (key) => this.userKeypairsRepository.findOneByOrFail({ userId: key }),
toRedisConverter: (value) => JSON.stringify(value),
fromRedisConverter: (value) => JSON.parse(value),
});
2022-09-17 18:27:08 +00:00
}
@bindThis
2022-09-17 18:27:08 +00:00
public async getUserKeypair(userId: User['id']): Promise<UserKeypair> {
return await this.cache.fetch(userId);
2022-09-17 18:27:08 +00:00
}
@bindThis
public dispose(): void {
this.cache.dispose();
}
@bindThis
public onApplicationShutdown(signal?: string | undefined): void {
this.dispose();
}
2022-09-17 18:27:08 +00:00
}