implementação do logger
This commit is contained in:
@@ -1,170 +1,127 @@
|
||||
/* eslint-disable prettier/prettier */
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
/*
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { IRedisClient } from '../core/configs/cache/IRedisClient';
|
||||
import { RedisClientToken } from '../core/configs/cache/redis-client.adapter.provider';
|
||||
import { DataConsultRepository } from './data-consult.repository';
|
||||
import { StoreDto } from './dto/store.dto';
|
||||
import { SellerDto } from './dto/seller.dto';
|
||||
import { BillingDto } from './dto/billing.dto';
|
||||
import { CustomerDto } from './dto/customer.dto';
|
||||
import { ProductDto } from './dto/product.dto';
|
||||
import { ILogger } from '../Log/ILogger';
|
||||
|
||||
https://docs.nestjs.com/providers#services
|
||||
*/
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { typeOrmConfig } from '../core/configs/typeorm.config';
|
||||
import { DataSource } from 'typeorm';
|
||||
const DEFAULT_CACHE_TTL = 100;
|
||||
|
||||
@Injectable()
|
||||
export class DataConsultService {
|
||||
constructor(
|
||||
private readonly repository: DataConsultRepository,
|
||||
@Inject(RedisClientToken)
|
||||
private readonly redisClient: IRedisClient,
|
||||
@Inject('LoggerService')
|
||||
private readonly logger: ILogger
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Método genérico para lidar com lógica de cache
|
||||
* @param cacheKey - A chave a ser usada para cache
|
||||
* @param fetchFn - Função para buscar dados se não estiverem no cache
|
||||
* @param ttl - Tempo de vida em segundos para o cache
|
||||
* @returns Os dados em cache ou recentemente buscados
|
||||
*/
|
||||
private async getCachedData<T>(
|
||||
cacheKey: string,
|
||||
fetchFn: () => Promise<T>,
|
||||
ttl: number = DEFAULT_CACHE_TTL
|
||||
): Promise<T> {
|
||||
try {
|
||||
this.logger.log(`Tentando obter dados em cache para a chave: ${cacheKey}`);
|
||||
const cached = await this.redisClient.get<T>(cacheKey);
|
||||
|
||||
async stores() {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
try {
|
||||
const sql = `SELECT PCFILIAL.CODIGO as "id"
|
||||
,PCFILIAL.RAZAOSOCIAL as "name"
|
||||
,PCFILIAL.CODIGO || ' - ' || PCFILIAL.FANTASIA as "store"
|
||||
FROM PCFILIAL
|
||||
WHERE PCFILIAL.CODIGO NOT IN ('99', '69')
|
||||
ORDER BY TO_NUMBER(PCFILIAL.CODIGO)`;
|
||||
if (cached) {
|
||||
this.logger.log(`Cache encontrado para a chave: ${cacheKey}`);
|
||||
return cached;
|
||||
}
|
||||
|
||||
this.logger.log(`Cache não encontrado para a chave: ${cacheKey}, buscando na origem`);
|
||||
const result = await fetchFn();
|
||||
|
||||
const stores = await queryRunner.manager.query(sql);
|
||||
try {
|
||||
await this.redisClient.set<T>(cacheKey, result, ttl);
|
||||
this.logger.log(`Dados armazenados em cache com sucesso para a chave: ${cacheKey}`);
|
||||
} catch (cacheError) {
|
||||
this.logger.warn(`Falha ao armazenar dados em cache para a chave: ${cacheKey}`);
|
||||
this.logger.error('Detalhes do erro de cache:', cacheError instanceof Error ? cacheError.stack : '');
|
||||
}
|
||||
|
||||
return stores;
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
await dataSource.destroy();
|
||||
}
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Erro no método getCachedData para a chave ${cacheKey}:`,
|
||||
error instanceof Error ? error.stack : ''
|
||||
);
|
||||
return fetchFn();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obter todas as lojas com cache
|
||||
* @returns Array de StoreDto
|
||||
*/
|
||||
async stores(): Promise<StoreDto[]> {
|
||||
this.logger.log('Buscando todas as lojas');
|
||||
return this.getCachedData<StoreDto[]>(
|
||||
'data-consult:stores',
|
||||
() => this.repository.findStores()
|
||||
);
|
||||
}
|
||||
|
||||
async sellers() {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
try {
|
||||
const sql = `SELECT PCUSUARI.CODUSUR as "id"
|
||||
,PCUSUARI.NOME as "name"
|
||||
FROM PCUSUARI
|
||||
WHERE PCUSUARI.DTTERMINO IS NULL
|
||||
AND PCUSUARI.TIPOVEND NOT IN ('P')
|
||||
ORDER BY PCUSUARI.NOME`;
|
||||
/**
|
||||
* Obter todos os vendedores com cache
|
||||
* @returns Array de SellerDto
|
||||
*/
|
||||
async sellers(): Promise<SellerDto[]> {
|
||||
this.logger.log('Buscando todos os vendedores');
|
||||
return this.getCachedData<SellerDto[]>(
|
||||
'data-consult:sellers',
|
||||
() => this.repository.findSellers()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obter todos os faturamentos com cache
|
||||
* @returns Array de BillingDto
|
||||
*/
|
||||
async billings(): Promise<BillingDto[]> {
|
||||
this.logger.log('Buscando todos os faturamentos');
|
||||
return this.getCachedData<BillingDto[]>(
|
||||
'data-consult:billings',
|
||||
() => this.repository.findBillings()
|
||||
);
|
||||
}
|
||||
|
||||
const sellers = await queryRunner.manager.query(sql);
|
||||
|
||||
return sellers;
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
await dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async billings() {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
try {
|
||||
const sql = `SELECT PCCOB.CODCOB as "id"
|
||||
,PCCOB.CODCOB||' - '||PCCOB.COBRANCA as "description"
|
||||
FROM PCCOB
|
||||
WHERE PCCOB.CODCOB NOT IN ('DEVP', 'DEVT', 'DESD')
|
||||
ORDER BY PCCOB.COBRANCA`;
|
||||
|
||||
|
||||
const sellers = await queryRunner.manager.query(sql);
|
||||
|
||||
return sellers;
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
await dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async customers(filter: string) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
try {
|
||||
let sql = `SELECT PCCLIENT.CODCLI as "id"
|
||||
,PCCLIENT.CODCLI || ' - '|| PCCLIENT.CLIENTE||
|
||||
' ( '||REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '')||' )' as "name"
|
||||
FROM PCCLIENT
|
||||
WHERE PCCLIENT.CODCLI = REGEXP_REPLACE('${filter}', '[^0-9]', '')
|
||||
ORDER BY PCCLIENT.CLIENTE`;
|
||||
let customers = await queryRunner.manager.query(sql);
|
||||
|
||||
if (customers.length == 0) {
|
||||
sql = `SELECT PCCLIENT.CODCLI as "id"
|
||||
,PCCLIENT.CODCLI || ' - '|| PCCLIENT.CLIENTE||
|
||||
' ( '||REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '')||' )' as "name"
|
||||
FROM PCCLIENT
|
||||
WHERE REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '') = REGEXP_REPLACE('${filter}', '[^0-9]', '')
|
||||
ORDER BY PCCLIENT.CLIENTE`;
|
||||
customers = await queryRunner.manager.query(sql);
|
||||
}
|
||||
|
||||
if (customers.length == 0) {
|
||||
sql = `SELECT PCCLIENT.CODCLI as "id"
|
||||
,PCCLIENT.CODCLI || ' - '|| PCCLIENT.CLIENTE||
|
||||
' ( '||REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '')||' )' as "name"
|
||||
FROM PCCLIENT
|
||||
WHERE PCCLIENT.CLIENTE LIKE '${filter.toUpperCase().replace('@', '%')}%'
|
||||
ORDER BY PCCLIENT.CLIENTE`;
|
||||
customers = await queryRunner.manager.query(sql);
|
||||
}
|
||||
|
||||
return customers;
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
await dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async products(filter: string) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
try {
|
||||
let sql = `SELECT PCPRODUT.CODPROD as "id"
|
||||
,PCPRODUT.CODPROD || ' - '|| PCPRODUT.DESCRICAO||
|
||||
' ( '||REGEXP_REPLACE(PCPRODUT.CODAUXILIAR, '[^0-9]', '')||' )' as "description"
|
||||
FROM PCPRODUT
|
||||
WHERE PCPRODUT.CODPROD = REGEXP_REPLACE('${filter}', '[^0-9]', '')
|
||||
ORDER BY PCPRODUT.DESCRICAO`;
|
||||
let products = await queryRunner.manager.query(sql);
|
||||
|
||||
if (products.length == 0) {
|
||||
sql = `SELECT PCPRODUT.CODPROD as "id"
|
||||
,PCPRODUT.CODPROD || ' - '|| PCPRODUT.DESCRICAO||
|
||||
' ( '||REGEXP_REPLACE(PCPRODUT.CODAUXILIAR, '[^0-9]', '')||' )' as "description"
|
||||
FROM PCPRODUT
|
||||
WHERE PCPRODUT.CODAUXILIAR = REGEXP_REPLACE('${filter}', '[^0-9]', '')
|
||||
ORDER BY PCPRODUT.DESCRICAO`;
|
||||
products = await queryRunner.manager.query(sql);
|
||||
}
|
||||
|
||||
if (products.length == 0) {
|
||||
sql = `SELECT PCPRODUT.CODPROD as "id"
|
||||
,PCPRODUT.CODPROD || ' - '|| PCPRODUT.DESCRICAO||
|
||||
' ( '||REGEXP_REPLACE(PCPRODUT.CODAUXILIAR, '[^0-9]', '')||' )' as "description"
|
||||
FROM PCPRODUT
|
||||
WHERE PCPRODUT.DESCRICAO LIKE '${filter}%'
|
||||
ORDER BY PCPRODUT.DESCRICAO`;
|
||||
products = await queryRunner.manager.query(sql);
|
||||
}
|
||||
|
||||
return products;
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
await dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obter clientes filtrados por termo de pesquisa com cache
|
||||
* @param filter - Termo de pesquisa para filtrar clientes
|
||||
* @returns Array de CustomerDto
|
||||
*/
|
||||
async customers(filter: string): Promise<CustomerDto[]> {
|
||||
this.logger.log(`Buscando clientes com filtro: ${filter}`);
|
||||
return this.getCachedData<CustomerDto[]>(
|
||||
`data-consult:customers:${filter}`,
|
||||
() => this.repository.findCustomers(filter)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obter produtos filtrados por termo de pesquisa com cache
|
||||
* @param filter - Termo de pesquisa para filtrar produtos
|
||||
* @returns Array de ProductDto
|
||||
*/
|
||||
async products(filter: string): Promise<ProductDto[]> {
|
||||
this.logger.log(`Buscando produtos com filtro: ${filter}`);
|
||||
return this.getCachedData<ProductDto[]>(
|
||||
`data-consult:products:${filter}`,
|
||||
() => this.repository.findProducts(filter)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user