Ajuste conexao oracle & postgres
This commit is contained in:
@@ -1,13 +1,10 @@
|
||||
import { BaseModule } from './core/services/base.module';
|
||||
import { BaseService } from './core/services/base.service';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { createOracleConfig } from './core/configs/typeorm.oracle.config';
|
||||
import { createPostgresConfig } from './core/configs/typeorm.postgres.config';
|
||||
import { LogisticModule } from './logistic/logistic.module';
|
||||
import { OrdersPaymentModule } from './orders-payment/orders-payment.module';
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
/* eslint-disable prettier/prettier */
|
||||
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { typeOrmConfig, typeOrmPgConfig } from './core/configs/typeorm.config';
|
||||
import { ProductsModule } from './products/products.module';
|
||||
import { AuthModule } from './auth/auth/auth.module';
|
||||
import { DataConsultModule } from './data-consult/data-consult.module';
|
||||
@@ -18,13 +15,22 @@ import { ReasonTableModule } from './crm/reason-table/reason-table.module';
|
||||
import { NegotiationsModule } from './crm/negotiations/negotiations.module';
|
||||
import { HttpModule } from '@nestjs/axios';
|
||||
import { LogisticController } from './logistic/logistic.controller';
|
||||
import { CacheModule } from './core/configs/cache/redis.module';
|
||||
import { LogisticService } from './logistic/logistic.service';
|
||||
import { LoggerModule } from './Log/logger.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
BaseModule,
|
||||
ConfigModule.forRoot({ isGlobal: true }), // necessário para ConfigService
|
||||
TypeOrmModule.forRootAsync({
|
||||
name: 'oracle',
|
||||
inject: [ConfigService],
|
||||
useFactory: createOracleConfig,
|
||||
}),
|
||||
TypeOrmModule.forRootAsync({
|
||||
name: 'postgres',
|
||||
inject: [ConfigService],
|
||||
useFactory: createPostgresConfig,
|
||||
}),
|
||||
LogisticModule,
|
||||
OrdersPaymentModule,
|
||||
HttpModule,
|
||||
@@ -36,14 +42,8 @@ import { LoggerModule } from './Log/logger.module';
|
||||
ProductsModule,
|
||||
AuthModule,
|
||||
OrdersModule,
|
||||
TypeOrmModule.forRoot(typeOrmConfig),
|
||||
TypeOrmModule.forRoot(typeOrmPgConfig),
|
||||
CacheModule,
|
||||
|
||||
],
|
||||
controllers: [
|
||||
OcorrencesController, LogisticController,],
|
||||
providers: [
|
||||
BaseService, LogisticService,],
|
||||
controllers: [OcorrencesController, LogisticController],
|
||||
providers: [ LogisticService],
|
||||
})
|
||||
export class AppModule { }
|
||||
export class AppModule {}
|
||||
|
||||
@@ -9,10 +9,10 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { UserModel } from '../../core/models/user.model';
|
||||
import { ResultModel } from '../../core/models/result.model';
|
||||
import { ResetPasswordModel } from '../../core/models/reset-password.model';
|
||||
import { ChangePasswordModel } from '../../core/models/change-password.model';
|
||||
import { UserModel } from 'src/core/models/user.model';
|
||||
import { ResultModel } from 'src/core/models/result.model';
|
||||
import { ResetPasswordModel } from 'src/core/models/reset-password.model';
|
||||
import { ChangePasswordModel } from 'src/core/models/change-password.model';
|
||||
|
||||
@Controller('api/v1/auth')
|
||||
export class AuthController {
|
||||
@@ -69,4 +69,4 @@ export class AuthController {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -29,4 +29,4 @@ export class AuthService {
|
||||
//return await this.accountService.findOneByUsername(payload.username);
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
}
|
||||
4
src/auth/users/dto/auth-request.dto.ts
Normal file
4
src/auth/users/dto/auth-request.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export class AuthRequestDto {
|
||||
userName: string;
|
||||
password: string;
|
||||
}
|
||||
6
src/auth/users/models/change-password.model.ts
Normal file
6
src/auth/users/models/change-password.model.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export class ChangePasswordModel {
|
||||
id: string;
|
||||
currentPassword: string;
|
||||
newPassword: string;
|
||||
}
|
||||
|
||||
5
src/auth/users/models/reset-password.model.ts
Normal file
5
src/auth/users/models/reset-password.model.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export class ResetPasswordModel {
|
||||
document: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
10
src/auth/users/models/user.model.ts
Normal file
10
src/auth/users/models/user.model.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
export interface UserModel {
|
||||
id: string;
|
||||
name: string;
|
||||
sellerId: string;
|
||||
storeId: string;
|
||||
email: string;
|
||||
username: string;
|
||||
dataDesligamento: Date | null;
|
||||
situacao: string;
|
||||
}
|
||||
@@ -7,4 +7,4 @@ import { UsersService } from './users.service';
|
||||
providers: [UsersService],
|
||||
exports: [UsersService],
|
||||
})
|
||||
export class UsersModule {}
|
||||
export class UsersModule {}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
describe('UsersService', () => {
|
||||
let service: UsersService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [UsersService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<UsersService>(UsersService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -1,17 +1,16 @@
|
||||
/* eslint-disable prettier/prettier */
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import md5 = require('md5');
|
||||
import { Guid } from "guid-typescript";
|
||||
import { typeOrmConfig } from '../../core/configs/typeorm.config';
|
||||
import { UserModel } from '../../core/models/user.model';
|
||||
|
||||
import { createOracleConfig } from '../../core/configs/typeorm.oracle.config';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private readonly configService: ConfigService) {}
|
||||
|
||||
async authenticate(user: any): Promise<any> {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createOracleConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -51,7 +50,7 @@ export class UsersService {
|
||||
}
|
||||
|
||||
async resetPassword(user: any): Promise<any> {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createOracleConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -105,7 +104,7 @@ export class UsersService {
|
||||
|
||||
|
||||
async changePassword(user: any): Promise<any> {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createOracleConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -149,4 +148,4 @@ export class UsersService {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,16 @@
|
||||
/* eslint-disable prettier/prettier */
|
||||
import { DataSourceOptions } from 'typeorm/data-source';
|
||||
import { registerAs } from '@nestjs/config';
|
||||
|
||||
export const typeOrmConfig: DataSourceOptions = {
|
||||
type: 'oracle',
|
||||
connectString: '(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 10.1.1.241)(PORT = 1521)))(CONNECT_DATA = (SERVICE_NAME = WINT)))',
|
||||
username: 'SEVEN',
|
||||
password: 'USR54SEV',
|
||||
synchronize: false,
|
||||
logging: false,
|
||||
entities: [__dirname + '/../**/*.entity.{js,ts}'],
|
||||
};
|
||||
|
||||
export const typeOrmPgConfig: DataSourceOptions = {
|
||||
type: 'postgres',
|
||||
host: '10.1.1.222',
|
||||
port: 5432,
|
||||
username: 'ti',
|
||||
password: 'ti',
|
||||
database: 'ksdb',
|
||||
synchronize: true,
|
||||
}
|
||||
export const databaseConfig = registerAs('database', () => ({
|
||||
oracle: {
|
||||
connectString: `(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = ${process.env.ORACLE_HOST})(PORT = ${process.env.ORACLE_PORT})))(CONNECT_DATA = (SERVICE_NAME = ${process.env.ORACLE_SERVICE})))`,
|
||||
username: process.env.ORACLE_USER,
|
||||
password: process.env.ORACLE_PASSWORD,
|
||||
},
|
||||
postgres: {
|
||||
host: process.env.POSTGRES_HOST,
|
||||
port: parseInt(process.env.POSTGRES_PORT || '5432', 10),
|
||||
username: process.env.POSTGRES_USER,
|
||||
password: process.env.POSTGRES_PASSWORD,
|
||||
database: process.env.POSTGRES_DB,
|
||||
},
|
||||
}));
|
||||
|
||||
14
src/core/configs/typeorm.oracle.config.ts
Normal file
14
src/core/configs/typeorm.oracle.config.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { DataSourceOptions } from 'typeorm';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
export function createOracleConfig(config: ConfigService): DataSourceOptions {
|
||||
return {
|
||||
type: 'oracle',
|
||||
connectString: config.get('ORACLE_CONNECT_STRING'),
|
||||
username: config.get('ORACLE_USER'),
|
||||
password: config.get('ORACLE_PASSWORD'),
|
||||
synchronize: false,
|
||||
logging: false,
|
||||
entities: [__dirname + '/../**/*.entity.{ts,js}'],
|
||||
};
|
||||
}
|
||||
15
src/core/configs/typeorm.postgres.config.ts
Normal file
15
src/core/configs/typeorm.postgres.config.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { DataSourceOptions } from 'typeorm';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
export function createPostgresConfig(config: ConfigService): DataSourceOptions {
|
||||
return {
|
||||
type: 'postgres',
|
||||
host: config.get('POSTGRES_HOST'),
|
||||
port: config.get('POSTGRES_PORT'),
|
||||
username: config.get('POSTGRES_USER'),
|
||||
password: config.get('POSTGRES_PASSWORD'),
|
||||
database: config.get('POSTGRES_DB'),
|
||||
synchronize: true,
|
||||
entities: [__dirname + '/../**/*.entity.{ts,js}'],
|
||||
};
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
import { DropAction } from './../../../node_modules/aws-sdk/clients/mailmanager.d';
|
||||
/*
|
||||
https://docs.nestjs.com/controllers#controllers
|
||||
*/
|
||||
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UseInterceptors,
|
||||
UploadedFile,
|
||||
} from '@nestjs/common';
|
||||
import { BaseService } from './base.service';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { diskStorage } from 'multer';
|
||||
import { extname } from 'path';
|
||||
import * as fs from 'fs';
|
||||
|
||||
@Controller('api/v1/base')
|
||||
export class BaseController {
|
||||
constructor(public readonly baseService: BaseService) {}
|
||||
// @UseGuards(JwtAuthGuard)
|
||||
@Get('execute-view')
|
||||
/* @ApiOperation({
|
||||
summary: 'Executa uma view com ou sem parâmetros',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'Dados retornados com sucesso.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 400,
|
||||
description: 'O nome da view é obrigatório.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 500,
|
||||
description: 'Erro ao executar a view.',
|
||||
})*/
|
||||
async executeView(
|
||||
@Query('viewName') viewName: string,
|
||||
@Query() params: Record<string, any>,
|
||||
) {
|
||||
if (!viewName) {
|
||||
throw new HttpException(
|
||||
'O nome da view é obrigatório.',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
try {
|
||||
return await this.baseService.executeView(viewName, params);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
`Erro ao executar a view: ${error.message}`,
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Post('send-image')
|
||||
@UseInterceptors(
|
||||
FileInterceptor('file', {
|
||||
storage: diskStorage({
|
||||
// Pasta onde os arquivos serão salvos; certifique-se que essa pasta exista ou crie-a automaticamente
|
||||
destination: './uploads',
|
||||
filename: (req, file, callback) => {
|
||||
// Gera um nome único para o arquivo
|
||||
const uniqueSuffix =
|
||||
Date.now() + '-' + Math.round(Math.random() * 1e9);
|
||||
const fileExtName = extname(file.originalname);
|
||||
callback(null, `${file.fieldname}-${uniqueSuffix}${fileExtName}`);
|
||||
},
|
||||
}),
|
||||
// Opcional: definir limites (ex.: tamanho máximo do arquivo)
|
||||
limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
|
||||
}),
|
||||
)
|
||||
async sendImage(
|
||||
@UploadedFile() file: Express.Multer.File,
|
||||
@Body('licensePlate') licensePlate: string,
|
||||
) {
|
||||
if (!file) {
|
||||
throw new HttpException('Nenhum arquivo enviado', HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// Aqui você pode processar o arquivo (ex.: enviar para o S3) ou armazená-lo no disco mesmo.
|
||||
// Neste exemplo, retornamos a URL do arquivo salvo localmente.
|
||||
this.baseService.sendImages('./uploads/' + file.filename);
|
||||
fs.unlink('./uploads/' + file.filename, () => {});
|
||||
return {
|
||||
success: true,
|
||||
message: 'Upload realizado com sucesso',
|
||||
url: `https://jur-saidaretornoveiculo.s3.sa-east-1.amazonaws.com/${file.filename}`,
|
||||
licensePlate,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { BaseController } from './base.controller';
|
||||
/*
|
||||
https://docs.nestjs.com/modules
|
||||
*/
|
||||
|
||||
import { Module } from '@nestjs/common';
|
||||
import { BaseService } from './base.service';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
controllers: [BaseController],
|
||||
providers: [BaseService],
|
||||
})
|
||||
export class BaseModule {}
|
||||
@@ -1,331 +0,0 @@
|
||||
import {
|
||||
Inject,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
} from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { typeOrmConfig } from '../configs/typeorm.config';
|
||||
import { S3 } from 'aws-sdk';
|
||||
import * as fs from 'fs';
|
||||
|
||||
@Injectable()
|
||||
export class BaseService {
|
||||
constructor() {}
|
||||
|
||||
async findAll(table: string) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const [rows] = await queryRunner.query(`SELECT * FROM ${table}`);
|
||||
return rows;
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao buscar todos os registros da tabela ${table}`,
|
||||
);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async findOne(table: string, id: any) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const [rows] = await queryRunner.query(
|
||||
`SELECT * FROM ${table} WHERE id = '${id}'`,
|
||||
);
|
||||
return rows[0];
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao buscar o registro com ID ${id} na tabela ${table}`,
|
||||
);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async create(table: string, data: any) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const columns = Object.keys(data)
|
||||
.map((key) => `${key}`)
|
||||
.join(', ');
|
||||
const values = Object.values(data);
|
||||
const placeholders = values.map(() => '?').join(', ');
|
||||
|
||||
const query = `INSERT INTO ${table} (${columns}) VALUES (${placeholders})`;
|
||||
|
||||
const [result] = await queryRunner.query(query, values);
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao criar um registro na tabela ${table}`,
|
||||
);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async update(table: string, where: any, data: any) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const [result] = await queryRunner.query(
|
||||
`UPDATE ${table} SET ${data} WHERE ${where}`,
|
||||
);
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao atualizar o registro com ${where} na tabela ${table}`,
|
||||
);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async delete(table: string, where: any) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const [result] = await queryRunner.query(
|
||||
`DELETE FROM ${table} WHERE ${where}`,
|
||||
);
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao deletar o registro com ID ${where} na tabela ${table}`,
|
||||
);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async query(queryString: string, params: any[]): Promise<any[]> {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const [rows] = await queryRunner.query(queryString, params);
|
||||
return rows as any[];
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao executar a consulta SQL personalizada`,
|
||||
);
|
||||
} finally {
|
||||
queryRunner.release();
|
||||
dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async executeView(viewName: string, params: Record<string, any>) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
// Valida se o nome da view foi fornecido
|
||||
if (!viewName) {
|
||||
throw new Error('O nome da view é obrigatório.');
|
||||
}
|
||||
|
||||
console.log(`Iniciando execução da view: ${viewName}`);
|
||||
console.log('Parâmetros recebidos:', params);
|
||||
|
||||
const conditions: string[] = [];
|
||||
const values: any[] = [];
|
||||
|
||||
// Remove o parâmetro viewName dos parâmetros antes de processar
|
||||
const filteredParams = { ...params };
|
||||
delete filteredParams.viewName;
|
||||
|
||||
// Adiciona as condições baseadas nos parâmetros fornecidos
|
||||
if (filteredParams && Object.keys(filteredParams).length > 0) {
|
||||
console.log('Adicionando condições para os parâmetros fornecidos...');
|
||||
for (const [key, value] of Object.entries(filteredParams)) {
|
||||
// Verifica se a chave e o valor são válidos
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
console.log(`Parâmetro válido: ${key} = '${value}'`);
|
||||
conditions.push(`${key} = '${value}'`); // Adiciona aspas para evitar problemas de SQL injection
|
||||
values.push(value);
|
||||
} else {
|
||||
console.warn(`Parâmetro ignorado: ${key} = '${value}'`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log('Nenhum parâmetro válido foi fornecido.');
|
||||
}
|
||||
|
||||
// Monta a cláusula WHERE somente se houver condições
|
||||
const whereClause =
|
||||
conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
||||
const query = `SELECT * FROM ${viewName} ${whereClause}`;
|
||||
|
||||
console.log(`Consulta SQL montada: ${query}`);
|
||||
console.log(`{Valores para a consulta:, ${values}`);
|
||||
|
||||
// Executa a consulta
|
||||
const rows = await queryRunner.query(query);
|
||||
|
||||
console.log(
|
||||
`Consulta executada com sucesso.Linhas retornadas: ${JSON.stringify(
|
||||
rows,
|
||||
)}`,
|
||||
);
|
||||
return rows;
|
||||
} catch (error) {
|
||||
console.error(`Erro ao executar a view ${viewName}: `, error.message);
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao executar a view ${viewName} com parâmetros.`,
|
||||
);
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
await dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async executeProcedure(procedureName: string, params: Record<string, any>) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
await queryRunner.startTransaction();
|
||||
try {
|
||||
const placeholders = Object.keys(params)
|
||||
.map(() => '?')
|
||||
.join(', ');
|
||||
const values = Object.values(params);
|
||||
|
||||
const query = `EXECUTE IMMEDIATE ${procedureName}(${placeholders})`;
|
||||
|
||||
// Log da query e dos valores
|
||||
console.log('Query executada:', query);
|
||||
console.log('Valores:', values);
|
||||
|
||||
const [result] = await queryRunner.query(query, values);
|
||||
|
||||
// Verifica e converte campos que contenham JSON strings para objetos
|
||||
const parsedResult = Array.isArray(result)
|
||||
? result.map((row) => {
|
||||
const parsedRow = { ...row };
|
||||
for (const [key, value] of Object.entries(parsedRow)) {
|
||||
try {
|
||||
// Tenta converter strings JSON para objetos
|
||||
if (
|
||||
typeof value === 'string' &&
|
||||
value.trim().startsWith('{') &&
|
||||
value.trim().endsWith('}')
|
||||
) {
|
||||
parsedRow[key] = JSON.parse(value);
|
||||
}
|
||||
} catch (error) {
|
||||
// Ignora se a conversão falhar
|
||||
console.warn(
|
||||
`Campo ${key} não é um JSON válido.Mantendo como string.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return parsedRow;
|
||||
})
|
||||
: result;
|
||||
|
||||
// Retorna os valores e o resultado
|
||||
return {
|
||||
message: 'Procedure executada com sucesso.',
|
||||
executedQuery: query,
|
||||
values: values,
|
||||
result: parsedResult,
|
||||
};
|
||||
} catch (error) {
|
||||
this.handleDatabaseError(
|
||||
error,
|
||||
`Erro ao executar a procedure ${procedureName} com parâmetros.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private handleDatabaseError(error: any, message: string): never {
|
||||
console.error(message, error); // Log detalhado do erro
|
||||
throw new InternalServerErrorException({
|
||||
message,
|
||||
sqlMessage: error.sqlMessage || error.message,
|
||||
sqlState: error.sqlState,
|
||||
});
|
||||
}
|
||||
|
||||
async sendImages(file: string) {
|
||||
// for (const file of files) {
|
||||
// const file = 'C:\\Temp\\brasil_2.jpg'
|
||||
if (file.endsWith('.jpg')) {
|
||||
const fileName = file; //directoryImages + '\\' + file;
|
||||
fs.readFile(fileName, (err, data) => {
|
||||
if (err) throw err;
|
||||
if (err) {
|
||||
console.log(`WRITE ERROR: ${err}`);
|
||||
} else {
|
||||
this.uploadS3(
|
||||
data,
|
||||
'jur-saidaretornoveiculo',
|
||||
file.replace('./uploads/', ''),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
//}
|
||||
}
|
||||
|
||||
async uploadS3(file, bucket, name) {
|
||||
const s3 = this.getS3();
|
||||
const params = {
|
||||
Bucket: bucket,
|
||||
Key: String(name),
|
||||
Body: file,
|
||||
};
|
||||
return new Promise((resolve, reject) => {
|
||||
s3.upload(params, (err, data) => {
|
||||
if (err) {
|
||||
console.log(JSON.stringify(err));
|
||||
reject(err.message);
|
||||
}
|
||||
resolve(data);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
getS3() {
|
||||
return new S3({
|
||||
accessKeyId: 'AKIAVHJOO6W765ZT2PNI', //process.env.AWS_ACCESS_KEY_ID,
|
||||
secretAccessKey: 'IFtP6Foc7JlE6TfR3psBAERUCMlH+4cRMx0GVIx2', // process.env.AWS_SECRET_ACCESS_KEY,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -34,10 +34,9 @@ export class DataConsultController {
|
||||
}
|
||||
|
||||
@Get('products/:filter')
|
||||
@ApiOperation({ summary: 'Filtra produtos pelo parâmetro fornecido' })
|
||||
@ApiParam({ name: 'filter', description: 'Filtro de busca para produtos' })
|
||||
@ApiOperation({ summary: 'Busca produtos filtrados' })
|
||||
@ApiParam({ name: 'filter', description: 'Filtro de busca' })
|
||||
async products(@Param('filter') filter: string) {
|
||||
return this.dataConsultService.products(filter);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -2,15 +2,15 @@ import { Module } from '@nestjs/common';
|
||||
import { DataConsultService } from './data-consult.service';
|
||||
import { DataConsultController } from './data-consult.controller';
|
||||
import { DataConsultRepository } from './data-consult.repository';
|
||||
import { CacheModule } from '../core/configs/cache/redis.module';
|
||||
import { LoggerModule } from 'src/Log/logger.module';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
|
||||
@Module({
|
||||
imports: [CacheModule,LoggerModule],
|
||||
imports: [LoggerModule, ConfigModule],
|
||||
controllers: [DataConsultController],
|
||||
providers: [
|
||||
DataConsultService,
|
||||
DataConsultRepository,
|
||||
],
|
||||
],
|
||||
})
|
||||
export class DataConsultModule {}
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { typeOrmConfig } from '../core/configs/typeorm.config';
|
||||
import { createOracleConfig } from '../core/configs/typeorm.oracle.config';
|
||||
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 { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Injectable()
|
||||
export class DataConsultRepository {
|
||||
private readonly dataSource: DataSource;
|
||||
|
||||
constructor() {
|
||||
this.dataSource = new DataSource(typeOrmConfig);
|
||||
constructor(private readonly configService: ConfigService) {
|
||||
this.dataSource = new DataSource(createOracleConfig(configService));
|
||||
this.dataSource.initialize();
|
||||
}
|
||||
|
||||
@@ -63,56 +64,64 @@ export class DataConsultRepository {
|
||||
}
|
||||
|
||||
async findCustomers(filter: string): Promise<CustomerDto[]> {
|
||||
if (!filter || typeof filter !== 'string') return [];
|
||||
|
||||
const cleanedNumeric = filter.replace(/[^\d]/g, '');
|
||||
const likeFilter = filter.toUpperCase().replace('@', '%') + '%';
|
||||
|
||||
const queries = [
|
||||
// Busca por código (apenas números)
|
||||
{
|
||||
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(?, '[^0-9]', '')
|
||||
WHERE PCCLIENT.CODCLI = :1
|
||||
ORDER BY PCCLIENT.CLIENTE
|
||||
`,
|
||||
params: [filter],
|
||||
params: [cleanedNumeric],
|
||||
},
|
||||
// Busca por CNPJ/CPF limpo
|
||||
{
|
||||
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(?, '[^0-9]', '')
|
||||
WHERE REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '') = :1
|
||||
ORDER BY PCCLIENT.CLIENTE
|
||||
`,
|
||||
params: [filter],
|
||||
params: [cleanedNumeric],
|
||||
},
|
||||
// Busca por nome do cliente
|
||||
{
|
||||
sql: `
|
||||
SELECT PCCLIENT.CODCLI as "id",
|
||||
PCCLIENT.CODCLI || ' - ' || PCCLIENT.CLIENTE ||
|
||||
' ( ' || REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '') || ' )' as "name"
|
||||
FROM PCCLIENT
|
||||
WHERE PCCLIENT.CLIENTE LIKE ?
|
||||
WHERE UPPER(PCCLIENT.CLIENTE) LIKE :1
|
||||
ORDER BY PCCLIENT.CLIENTE
|
||||
`,
|
||||
params: [filter.toUpperCase().replace('@', '%') + '%'],
|
||||
params: [likeFilter],
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
for (const { sql, params } of queries) {
|
||||
const result = await this.executeQuery<CustomerDto[]>(sql, params);
|
||||
if (result.length > 0) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
|
||||
async findProducts(filter: string): Promise<ProductDto[]> {
|
||||
const cleanFilter = filter.replace(/[^\d]/g, '');
|
||||
const cleanedFilter = filter.replace(/[^\d]/g, ''); // apenas números
|
||||
const likeFilter = filter + '%';
|
||||
const codAux = filter.replace(/[^\d]/g, '');
|
||||
|
||||
const queries = [
|
||||
{
|
||||
@@ -124,7 +133,7 @@ export class DataConsultRepository {
|
||||
WHERE PCPRODUT.CODPROD = ?
|
||||
ORDER BY PCPRODUT.DESCRICAO
|
||||
`,
|
||||
params: [cleanFilter],
|
||||
params: [cleanedFilter],
|
||||
},
|
||||
{
|
||||
sql: `
|
||||
@@ -135,7 +144,7 @@ export class DataConsultRepository {
|
||||
WHERE PCPRODUT.CODAUXILIAR = ?
|
||||
ORDER BY PCPRODUT.DESCRICAO
|
||||
`,
|
||||
params: [codAux],
|
||||
params: [cleanedFilter],
|
||||
},
|
||||
{
|
||||
sql: `
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { IRedisClient } from '../core/configs/cache/IRedisClient';
|
||||
import { RedisClientToken } from '../core/configs/cache/redis-client.adapter.provider';
|
||||
import { Injectable, HttpException, HttpStatus, Inject } from '@nestjs/common';
|
||||
import { DataConsultRepository } from './data-consult.repository';
|
||||
import { StoreDto } from './dto/store.dto';
|
||||
import { SellerDto } from './dto/seller.dto';
|
||||
@@ -9,119 +7,73 @@ import { CustomerDto } from './dto/customer.dto';
|
||||
import { ProductDto } from './dto/product.dto';
|
||||
import { ILogger } from '../Log/ILogger';
|
||||
|
||||
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);
|
||||
|
||||
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();
|
||||
|
||||
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 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
|
||||
* Obter todas as lojas
|
||||
* @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()
|
||||
);
|
||||
return this.repository.findStores();
|
||||
}
|
||||
|
||||
/**
|
||||
* Obter todos os vendedores com cache
|
||||
* Obter todos os vendedores
|
||||
* @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()
|
||||
);
|
||||
return this.repository.findSellers();
|
||||
}
|
||||
|
||||
/**
|
||||
* Obter todos os faturamentos com cache
|
||||
* Obter todos os faturamentos
|
||||
* @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()
|
||||
);
|
||||
return this.repository.findBillings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Obter clientes filtrados por termo de pesquisa com cache
|
||||
* Obter clientes filtrados por termo de pesquisa
|
||||
* @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)
|
||||
);
|
||||
return this.repository.findCustomers(filter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obter produtos filtrados por termo de pesquisa com cache
|
||||
* Obter produtos filtrados por termo de pesquisa
|
||||
* @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)
|
||||
);
|
||||
|
||||
try {
|
||||
const result = await this.repository.findProducts(filter);
|
||||
this.logger.log(`Produtos encontrados: ${result.length}`);
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Erro ao buscar produtos com filtro "${filter}"`,
|
||||
error instanceof Error ? error.stack : ''
|
||||
);
|
||||
|
||||
throw new HttpException(
|
||||
'Erro ao buscar produtos. Tente novamente mais tarde.',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { Get, HttpException, HttpStatus, Injectable, Query, UseGuards } from '@nestjs/common';
|
||||
import { typeOrmConfig, typeOrmPgConfig } from '../core/configs/typeorm.config';
|
||||
import { createOracleConfig } from '../core/configs/typeorm.oracle.config';
|
||||
import { createPostgresConfig } from '../core/configs/typeorm.postgres.config';
|
||||
import { CarOutDelivery } from '../core/models/car-out-delivery.model';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { CarInDelivery } from '../core/models/car-in-delivery.model';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Injectable()
|
||||
export class LogisticService {
|
||||
constructor(private readonly configService: ConfigService) {}
|
||||
|
||||
async getExpedicao() {
|
||||
const dataSource = new DataSource(typeOrmPgConfig);
|
||||
const dataSource = new DataSource(createPostgresConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -95,7 +98,7 @@ export class LogisticService {
|
||||
}
|
||||
|
||||
async getDeliveries(placa: string) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createPostgresConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -139,7 +142,7 @@ export class LogisticService {
|
||||
}
|
||||
|
||||
async getStatusCar(placa: string) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createPostgresConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -163,7 +166,7 @@ export class LogisticService {
|
||||
}
|
||||
|
||||
async getEmployee() {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createPostgresConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -186,7 +189,7 @@ export class LogisticService {
|
||||
|
||||
async createCarOut(data: CarOutDelivery) {
|
||||
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createPostgresConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -261,7 +264,7 @@ export class LogisticService {
|
||||
|
||||
async createCarIn(data: CarInDelivery) {
|
||||
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createPostgresConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
|
||||
@@ -23,6 +23,6 @@ async function bootstrap() {
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('docs', app, document);
|
||||
|
||||
await app.listen(9002);
|
||||
await app.listen(9009);
|
||||
}
|
||||
bootstrap();
|
||||
|
||||
@@ -6,14 +6,16 @@ https://docs.nestjs.com/providers#services
|
||||
*/
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { typeOrmConfig } from '../core/configs/typeorm.config';
|
||||
import { createOracleConfig } from '../core/configs/typeorm.oracle.config';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Injectable()
|
||||
export class OrdersPaymentService {
|
||||
constructor(private readonly configService: ConfigService) {}
|
||||
|
||||
async findOrders(storeId: string, orderId: number) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createOracleConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -58,7 +60,7 @@ export class OrdersPaymentService {
|
||||
}
|
||||
|
||||
async findPayments(orderId: number) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createOracleConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -90,7 +92,7 @@ export class OrdersPaymentService {
|
||||
}
|
||||
|
||||
async createPayment(payment: any) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createOracleConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -116,7 +118,7 @@ export class OrdersPaymentService {
|
||||
|
||||
async createInvoice(data: any) {
|
||||
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createOracleConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,15 +6,16 @@ https://docs.nestjs.com/providers#services
|
||||
*/
|
||||
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { typeOrmConfig } from '../core/configs/typeorm.config';
|
||||
import { createOracleConfig } from '../core/configs/typeorm.oracle.config';
|
||||
import { ExposedProduct } from '../core/models/exposed-product.model';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Injectable()
|
||||
export class ProductsService {
|
||||
|
||||
constructor(private readonly configService: ConfigService) {}
|
||||
async productsValidation(storeId: string, filtro: string): Promise<any> {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createOracleConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -76,7 +77,7 @@ export class ProductsService {
|
||||
}
|
||||
|
||||
async exposedProduct(product: ExposedProduct) {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createOracleConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
@@ -97,7 +98,7 @@ export class ProductsService {
|
||||
}
|
||||
|
||||
async getProductsEcommerce() {
|
||||
const dataSource = new DataSource(typeOrmConfig);
|
||||
const dataSource = new DataSource(createOracleConfig(this.configService));
|
||||
await dataSource.initialize();
|
||||
const queryRunner = dataSource.createQueryRunner();
|
||||
await queryRunner.connect();
|
||||
|
||||
Reference in New Issue
Block a user