FEAT: Connection test creating connection

- If any error occurs, connection is deleted
 - If operation_result is false, connection is deleted
This commit is contained in:
Gabriel Rosa
2022-08-03 11:31:57 -03:00
parent a1cdad42ab
commit 688bf49f3b
11 changed files with 201 additions and 124 deletions
+19 -3
View File
@@ -1,16 +1,32 @@
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';
import ErrorBuilder from '../utils/ErrorBuilder';
/**
* ExceptionFilter to handle RpcException thrown by our microservices
*
* If it detects that the exception is already an **HttpException** or it is generated by our **ErrorBuilder**,
* it will return the exception without any treatment.
*/
@Catch(Error)
export class GrpcToHttpExceptionFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
// return this exception directly if is already of type ErrorBuilder,
// else transform it using the ErrorBuilder
if (exception instanceof HttpException) {
return response
.status(exception.getStatus())
.json(exception.getResponse());
}
const err =
exception.constructor.name === ErrorBuilder.name
? exception
@@ -5,6 +5,7 @@ import {
HttpStatus,
Inject,
Post,
UseFilters,
ValidationPipe,
} from '@nestjs/common';
import { ApiOkResponse, ApiTags } from '@nestjs/swagger';
@@ -24,9 +25,11 @@ import {
} from './dto/connection-test';
import { DadosferaLogger } from 'dadosfera-logs';
import { Authenticated } from 'src/authentication/authentication.decorator';
import { GrpcToHttpExceptionFilter } from 'src/error/grpc-to-http-exception.filter';
@ApiTags('Connection Test')
@Controller('connection-test')
@UseFilters(new GrpcToHttpExceptionFilter())
@Authenticated()
export class ConnectionTestController {
logger: any;
@@ -60,16 +63,13 @@ export class ConnectionTestController {
@HttpCode(HttpStatus.OK)
async connectionTestCredentials(
@User() user: RequestUser,
@Body(new ValidationPipe()) body: ConnectionTestCredentialsReq,
@Body() body: ConnectionTestCredentialsReq,
) {
this.logger.info('/connection-test/credentials', {
user: user.user_id,
customer: user.customer_name,
});
return this.connectionTestService.connectionTestCredentials(
body,
user.customer_name,
);
return this.connectionTestService.connectionTestCredentials(body, user);
}
@Post('schemas')
@@ -113,7 +113,7 @@ export class ConnectionTestController {
@User() user: RequestUser,
@Body(new ValidationPipe()) body: GetTableMetadataReq,
) {
this.logger.info('/connection-test/tables', {
this.logger.info('/connection-test/table-metadata', {
user: user.user_id,
customer: user.customer_name,
});
@@ -4,10 +4,11 @@ import { ConnectionTestService } from './connection-test.service';
import { DadosferaLogger } from 'dadosfera-logs';
import { ClientsModule } from '@nestjs/microservices';
import { ConnectionTestClientConfiguration } from './connection-test-client.config';
import { ConnectionModule } from '../connection/connection.module';
const client = new ConnectionTestClientConfiguration();
@Module({
controllers: [ConnectionTestController],
providers: [ConnectionTestService, DadosferaLogger],
imports: [ClientsModule.register([client.providerOptions])],
imports: [ClientsModule.register([client.providerOptions]), ConnectionModule],
})
export class ConnectionTestModule {}
@@ -14,12 +14,17 @@ import {
GetTableMetadataReq,
GetTableMetadataRes,
} from './dto/connection-test';
import { ConnectionClientService } from '../connection/client.service';
import { CreateConnectionDto } from '../connection/dtos/create-connection';
import { Info } from 'protospack/dist/lib/interfaces';
import { RequestUser } from 'src/authentication/user.decorator';
@Injectable()
export class ConnectionTestService {
private connectionTestReadClient: ConnectionTest.ReadService.ConnectionTestReadServices;
constructor(
@Inject('ConnectionTestGrpcClient') private readonly grpcClient: ClientGrpc,
private connectionsService: ConnectionClientService,
) {
this.connectionTestReadClient =
grpcClient.getService<ConnectionTest.ReadService.ConnectionTestReadServices>(
@@ -44,19 +49,45 @@ export class ConnectionTestService {
}
async connectionTestCredentials(
body: ConnectionTestCredentialsReq,
customer_name: string,
user: RequestUser,
): Promise<ConnectionTestCredentialsRes> {
const { connector_id, plugin } = body;
//CREATE CONNECTION
const connection_id = '';
/***********************/
const { plugin, ...connectionBody } = body;
let { connection_id } = body;
const { customer_id, customer_name, user_id } = user;
/********* CREATE CONNECTION *********/
if (!connection_id) {
if (!connectionBody.properties.credentials_type)
connectionBody.properties.credentials_type = 'basic_auth';
const createConnectionBody: CreateConnectionDto = {
...connectionBody,
};
const { connection } = await this.connectionsService.createConnection({
body: createConnectionBody,
info: { customer_id, customer_name, user_id },
});
connection_id = connection.id;
}
/************************************/
const { operation_result } = await lastValueFrom(
this.connectionTestReadClient.ConnectionTestCredentials({
connection_id,
customer_name,
plugin,
}),
);
).catch(async (e) => {
await this.connectionsService.deleteConnection({
body: { id: connection_id },
info: { customer_id, customer_name, user_id },
});
throw e;
});
if (!operation_result)
await this.connectionsService.deleteConnection({
body: { id: connection_id },
info: { customer_id, customer_name, user_id },
});
return { operation_result, connection_id };
}
async connectionTestListSchemas(
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional, OmitType } from '@nestjs/swagger';
import { IsString, IsObject, IsOptional } from 'class-validator';
import { IsString, IsOptional } from 'class-validator';
import { DatabaseConnectionPropertiesDto } from 'src/modules/connection/dtos/connection';
import { CreateConnectionDto } from 'src/modules/connection/dtos/create-connection';
export class ColumnDto {
@@ -44,11 +44,13 @@ export class ConnectionTestCredentialsReq extends OmitType(
['properties'],
) {
@ApiProperty()
@IsString()
plugin: string;
@ApiProperty()
@IsObject()
properties: DatabaseConnectionPropertiesDto;
@ApiPropertyOptional()
connection_id?: string;
}
export class ConnectionTestCredentialsRes {
@@ -116,5 +118,5 @@ export class GetTableMetadataReq {
export class GetTableMetadataRes {
@ApiProperty({ type: [TableMetadataDto] })
table_metadata: TableMetadataDto[];
tables_metadata: TableMetadataDto[];
}
@@ -18,5 +18,6 @@ const client = new ConnectionClientConfiguration();
},
]),
],
exports: [ConnectionClientService],
})
export class ConnectionModule {}
+26 -1
View File
@@ -171,6 +171,31 @@ export function EnrichErrorCode(code: string) {
message: 'Id encontra-se num formato inválido',
code,
};
case ErrorCodes.CONNECTION_TEST.ERROR:
return {
statusCode: HttpStatus.BAD_REQUEST,
error: 'Erro ao realizar o teste',
message: 'Verifique os dados de conexão e tente novamente',
code,
};
case ErrorCodes.CONNECTION_TEST.EXPIRED:
return {
statusCode: HttpStatus.NOT_FOUND,
error: 'Teste de conexão expirado',
message: 'Favor realizar novo teste',
code,
};
case ErrorCodes.CONNECTION_TEST.TIMEOUT:
return {
statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
error: 'Tempo limite excedido',
message:
'O teste excedeu o tempo limite. Verifique os dados de conexão e tente novamente',
code,
};
case ErrorCodes.INTERNAL:
case ErrorCodes.UNKNOWN:
default:
@@ -193,7 +218,7 @@ export default class ErrorBuilder extends HttpException {
constructor(code: string | RpcException = '') {
if (typeof code !== 'string') {
logger.log(code?.stack);
code = (code as any).details as string;
code = (code as any)?.details as string;
} else {
logger.log(code);
}
+8
View File
@@ -38,6 +38,13 @@ const TERMS_OF_USE = {
REQUIRED: 'TERMS_OF_USE.REQUIRED',
};
const CONNECTION_TEST = {
ERROR: 'CONNECTION_TEST.ERROR',
EXPIRED: 'CONNECTION_TEST.EXPIRED',
TIMEOUT: 'CONNECTION_TEST.TIMEOUT',
UNKNOWN: 'CONNECTION_TEST.UNKNOWN',
};
const ErrorCodes = {
UNKNOWN: 'UNKNOWN',
RATE_LIMIT: 'RATE_LIMIT',
@@ -47,6 +54,7 @@ const ErrorCodes = {
TERMS_OF_USE,
USER,
CUSTOMER,
CONNECTION_TEST,
};
export default ErrorCodes;