feat: implement project settings management with CRUD operations and caching

This commit is contained in:
lborv
2025-10-13 20:40:01 +03:00
parent aa7920384c
commit 93f12cd1d8
14 changed files with 304 additions and 17 deletions

View File

@ -0,0 +1,112 @@
import { Inject, Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { ProjectSetting } from "./entities/project.setting.entity";
import { RedisClient } from "src/redis/redis.service";
@Injectable()
export class ProjectSettingService {
constructor(
@InjectRepository(ProjectSetting)
private readonly projectSettingRepository: Repository<ProjectSetting>,
@Inject(RedisClient)
private readonly redisClient: RedisClient
) {}
async updateCache(projectId: string) {
const settings = await this.projectSettingRepository.find({
where: { project: { id: projectId } },
});
const settingsObject = settings.reduce((obj, setting) => {
obj[setting.key] = setting.value;
return obj;
}, {});
await this.redisClient.set(
`project_settings_${projectId}`,
settingsObject,
300
);
return settingsObject;
}
async get(key: string, projectId: string) {
const cached = await this.redisClient.get(`project_settings_${projectId}`);
if (cached && key in cached) {
return cached[key];
}
const setting = await this.projectSettingRepository.findOne({
where: { project: { id: projectId }, key },
});
if (setting) {
return setting.value;
}
return null;
}
async getAll(projectId: string) {
const cached = await this.redisClient.get(`project_settings_${projectId}`);
if (cached) {
return cached;
}
const settings = await this.projectSettingRepository.find({
where: { project: { id: projectId } },
});
const settingsObject = settings.reduce((obj, setting) => {
obj[setting.key] = setting.value;
return obj;
}, {});
await this.redisClient.set(
`project_settings_${projectId}`,
settingsObject,
300
);
return settingsObject;
}
async create(projectId: string, key: string, value: string) {
const existingSetting = await this.projectSettingRepository.findOne({
where: { project: { id: projectId }, key },
});
if (existingSetting) {
existingSetting.value = value;
await this.projectSettingRepository.save(existingSetting);
return await this.updateCache(projectId);
}
const newSetting = this.projectSettingRepository.create({
key,
value,
project: { id: projectId },
});
await this.projectSettingRepository.save(newSetting);
return await this.updateCache(projectId);
}
async delete(projectId: string, key: string) {
const setting = await this.projectSettingRepository.findOne({
where: { project: { id: projectId }, key },
});
if (setting) {
await this.projectSettingRepository.remove(setting);
}
return await this.updateCache(projectId);
}
}