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

35 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-09-17 21:27:08 +03:00
import { Inject, Injectable } from '@nestjs/common';
import Redis from 'ioredis';
2022-09-17 21:27:08 +03:00
import type { User } from '@/models/entities/User.js';
2022-09-20 23:33:11 +03:00
import type { UserKeypairsRepository } from '@/models/index.js';
import { RedisKVCache } from '@/misc/cache.js';
2022-09-17 21:27:08 +03:00
import type { UserKeypair } from '@/models/entities/UserKeypair.js';
import { DI } from '@/di-symbols.js';
import { bindThis } from '@/decorators.js';
2022-09-17 21:27:08 +03:00
@Injectable()
export class UserKeypairService {
private cache: RedisKVCache<UserKeypair>;
2022-09-17 21:27:08 +03:00
constructor(
@Inject(DI.redis)
private redisClient: Redis.Redis,
2022-09-17 21:27:08 +03: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 21:27:08 +03:00
}
@bindThis
2022-09-17 21:27:08 +03:00
public async getUserKeypair(userId: User['id']): Promise<UserKeypair> {
return await this.cache.fetch(userId);
2022-09-17 21:27:08 +03:00
}
}