Added caching

This commit is contained in:
2024-02-14 22:44:29 +03:00
parent 8919c305c4
commit 4b78993a82
4 changed files with 53 additions and 8 deletions

View File

@@ -1,11 +1,16 @@
import { Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Inject, Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Cache } from 'cache-manager';
import { Admin } from 'libs/database/admin.entity';
import { Repository } from 'typeorm';
@Injectable()
export class AdminService {
private readonly logger: Logger = new Logger(AdminService.name);
constructor(@InjectRepository(Admin) private adminRepository: Repository<Admin>) {}
constructor(
@InjectRepository(Admin) private adminRepository: Repository<Admin>,
@Inject(CACHE_MANAGER) private cacheManager: Cache,
) {}
async getAdmins() {
try {
@@ -24,13 +29,17 @@ export class AdminService {
async checkIsAdmin(id: string) {
try {
this.logger.debug(`[admin.checkIsAdmin]`);
const is_admin = await this.cacheManager.get(`admin_${id}`);
if (is_admin) return is_admin;
const admins = await this.adminRepository.findOne({
relations: { user: true },
where: { user: { id: id } },
});
if (!admins) {
await this.cacheManager.set(`admin_${id}`, false, { ttl: 10 } as any);
return false;
}
await this.cacheManager.set(`admin_${id}`, true, { ttl: 10 } as any);
return true;
} catch (error) {
this.logger.debug(`[checkIsAdmin] ${JSON.stringify({ error })}`);

View File

@@ -1,4 +1,5 @@
import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
import { CacheInterceptor, CacheKey, CacheTTL } from '@nestjs/cache-manager';
import { Body, Controller, Delete, Get, Param, Post, UseInterceptors } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { ICreateBotSettingsProfile, IEditBotSettingsProfile } from './settings.dto';
import { SettingsService } from './settings.service';
@@ -12,10 +13,19 @@ export class SettingsController {
@ApiOperation({ description: 'Get settings for bot' })
@Get()
@CacheKey('settings')
@CacheTTL({ ttl: 600 } as any)
@UseInterceptors(CacheInterceptor)
async getSettings() {
return await this.settingsService.getSettings();
}
@ApiOperation({ description: 'Get active settings' })
@Get('active')
async getActiveSettings() {
return await this.settingsService.getActiveSettings();
}
@ApiOperation({ description: 'Get all bot settings profiles' })
@Get('profile')
async getProfiles() {

View File

@@ -1,11 +1,17 @@
import { HttpException, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { HttpException, Inject, Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Cache } from 'cache-manager';
import { BotSettings } from 'libs/database/settings.entity';
import { Repository } from 'typeorm';
import { ICreateBotSettingsProfile, IEditBotSettingsProfile } from './settings.dto';
@Injectable()
export class SettingsService {
constructor(@InjectRepository(BotSettings) private botSettingsRepository: Repository<BotSettings>) {}
constructor(
@InjectRepository(BotSettings) private botSettingsRepository: Repository<BotSettings>,
@Inject(CACHE_MANAGER) private cacheManager: Cache,
) {}
private readonly logger: Logger = new Logger(SettingsService.name);
async getSettings() {
@@ -16,8 +22,18 @@ export class SettingsService {
throw new HttpException('No settings found', 404);
}
async getActiveSettings() {
this.logger.debug('[settings.getActiveSettings]');
const settings = await this.botSettingsRepository.findOneBy({ isActive: true });
await this.cacheManager.set('settings', settings, { ttl: 600 } as any);
if (settings) return settings;
this.logger.debug(`[settings.getActiveSettings] No active settings found`);
throw new HttpException('No settings found', 404);
}
async newProfile(data: ICreateBotSettingsProfile) {
this.logger.log(`[settings.newProfile] data: ${JSON.stringify(data)}`);
await this.cacheManager.del('settings');
return await this.botSettingsRepository.save({ channel: data.channel, messageTimes: data.postTimes });
}
@@ -28,6 +44,7 @@ export class SettingsService {
async editProfile(data: IEditBotSettingsProfile) {
this.logger.log(`[settings.editProfile] data: ${JSON.stringify(data)}`);
await this.cacheManager.del('settings');
const editProfile = await this.botSettingsRepository.findOneBy({ uuid: data.uuid });
if (!editProfile) {
this.logger.debug(`[settings.editProfile] No profile found`);
@@ -50,6 +67,7 @@ export class SettingsService {
async deleteProfile(profile_uuid: string) {
this.logger.log(`[settings.deleteProfile] uuid: ${profile_uuid}`);
await this.cacheManager.del('settings');
const deleteProfile = await this.botSettingsRepository.findOneBy({ uuid: profile_uuid });
if (!deleteProfile) {
this.logger.debug(`[settings.deleteProfile] No profile found`);

View File

@@ -1,5 +1,7 @@
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { HttpException, HttpStatus, Inject, Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Cache } from 'cache-manager';
import { User } from 'libs/database/user.entity';
import { Repository } from 'typeorm';
import { IGetUser } from './user.dto';
@@ -7,18 +9,24 @@ import { IGetUser } from './user.dto';
@Injectable()
export class UserService {
private readonly logger: Logger = new Logger(UserService.name);
constructor(@InjectRepository(User) private userRepository: Repository<User>) {}
constructor(
@InjectRepository(User) private userRepository: Repository<User>,
@Inject(CACHE_MANAGER) private cacheManager: Cache,
) {}
async getUser(data: IGetUser) {
try {
this.logger.debug(`[user.getUser] data: ${JSON.stringify(data)}`);
let user = await this.userRepository.findOne({
let user = await this.cacheManager.get(`user_${data.id}`);
if (user) return user;
user = await this.userRepository.findOne({
where: { id: data.id },
});
if (!user) {
user = await this.userRepository.save({ id: data.id, user_name: data.username });
this.logger.log(`User ${data.id} created`);
}
await this.cacheManager.set(`user_${data.id}`, user, { ttl: 600 } as any);
return user;
} catch (error) {
this.logger.debug(`[user.getUser] ${JSON.stringify({ error })}`);