Files
public-pool/src/ORM/client/client.service.ts
T
2023-07-23 00:15:48 -04:00

87 lines
2.4 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ClientEntity } from './client.entity';
@Injectable()
export class ClientService {
constructor(
@InjectRepository(ClientEntity)
private clientRepository: Repository<ClientEntity>
) {
}
public async save(client: Partial<ClientEntity>) {
return await this.clientRepository.save(client);
}
public async delete(sessionId: string) {
return await this.clientRepository.softDelete({ sessionId });
}
public async deleteOldClients() {
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
return await this.clientRepository
.createQueryBuilder()
.delete()
.from(ClientEntity)
.where('deletedAt < :time', { time: oneDayAgo })
.execute();
}
public async updateBestDifficulty(sessionId: string, bestDifficulty: number) {
return await this.clientRepository.update({ sessionId }, { bestDifficulty });
}
public async connectedClientCount(): Promise<number> {
return await this.clientRepository.count();
}
public async getBestDiff(address: string) {
const res = await this.clientRepository.createQueryBuilder('client')
.select('MAX(client.bestDifficulty)', 'bestDifficulty')
.where('client.address = :address', { address })
.withDeleted()
.getRawOne();
return res?.bestDifficulty;
}
public async getByAddress(address: string): Promise<ClientEntity[]> {
return await this.clientRepository.find({
where: {
address
}
})
}
public async getByName(address: string, clientName: string): Promise<ClientEntity[]> {
return await this.clientRepository.find({
where: {
address,
clientName
}
})
}
public async getBySessionId(address: string, clientName: string, sessionId: string): Promise<ClientEntity> {
return await this.clientRepository.findOne({
where: {
address,
clientName,
sessionId
}
})
}
public async deleteAll() {
return await this.clientRepository.softDelete({})
}
}