72 lines
1.8 KiB
TypeScript
72 lines
1.8 KiB
TypeScript
import { Inject, Injectable } from "@nestjs/common";
|
|
import { Repository } from "typeorm";
|
|
import { Query } from "../entities/query.entity";
|
|
import { InjectRepository } from "@nestjs/typeorm";
|
|
import { ProjectService } from "src/project/project.service";
|
|
import { RedisClient } from "src/redis/redis.service";
|
|
|
|
@Injectable()
|
|
export class QueryHandlerService {
|
|
constructor(
|
|
@InjectRepository(Query)
|
|
private readonly queryRepository: Repository<Query>,
|
|
@Inject(ProjectService)
|
|
private readonly projectService: ProjectService,
|
|
@Inject(RedisClient)
|
|
private readonly redisClient: RedisClient
|
|
) {}
|
|
|
|
async createQuery(
|
|
queryData: { projectToken: string; source: string },
|
|
isCommand = false
|
|
) {
|
|
const project = await this.projectService.findById(queryData.projectToken);
|
|
|
|
if (!project) {
|
|
throw new Error("Project not found");
|
|
}
|
|
|
|
queryData["project"] = project;
|
|
queryData["isCommand"] = isCommand ? 1 : 0;
|
|
delete queryData.projectToken;
|
|
|
|
const query = this.queryRepository.create(queryData);
|
|
|
|
await this.queryRepository.save(query);
|
|
|
|
return query;
|
|
}
|
|
|
|
async getQueryById(id: string) {
|
|
const cached = await this.redisClient.get(`query_${id}`);
|
|
|
|
if (cached) {
|
|
return cached;
|
|
}
|
|
|
|
const query = await this.queryRepository.findOne({
|
|
where: { id },
|
|
relations: ["project"],
|
|
});
|
|
|
|
if (query) {
|
|
await this.redisClient.set(`query_${id}`, query, 300);
|
|
}
|
|
|
|
return query;
|
|
}
|
|
|
|
async updateQuery(id: string, updateData: Partial<Query>) {
|
|
const query = await this.queryRepository.findOne({ where: { id } });
|
|
|
|
if (!query) {
|
|
throw new Error("Query not found");
|
|
}
|
|
|
|
await this.redisClient.del(`query_${id}`);
|
|
|
|
Object.assign(query, updateData);
|
|
return this.queryRepository.save(query);
|
|
}
|
|
}
|