72 lines
2.2 KiB
Dart
72 lines
2.2 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:http/http.dart' as http;
|
|
|
|
import '../../../domain/repositories/connection_tester.dart';
|
|
import 'odoo_api_uri_builder.dart';
|
|
|
|
class OdooConnectionTester implements ConnectionTester {
|
|
OdooConnectionTester({http.Client? client})
|
|
: _client = client ?? http.Client();
|
|
|
|
static const _timeout = Duration(seconds: 10);
|
|
final http.Client _client;
|
|
|
|
@override
|
|
Future<ConnectionTestResult> test(Uri serverUri) async {
|
|
final healthUri = OdooApiUriBuilder.endpoint(serverUri, '/pdv_pos/health');
|
|
try {
|
|
final request = http.Request('GET', healthUri)
|
|
..followRedirects = false
|
|
..headers['Accept'] = 'application/json';
|
|
final response = await _client
|
|
.send(request)
|
|
.then(http.Response.fromStream)
|
|
.timeout(_timeout);
|
|
if (response.statusCode != HttpStatus.ok) {
|
|
return ConnectionTestResult(
|
|
isAvailable: false,
|
|
message: 'O servidor respondeu com erro HTTP ${response.statusCode}.',
|
|
);
|
|
}
|
|
|
|
final body = jsonDecode(response.body);
|
|
if (body is Map<String, dynamic> &&
|
|
body['status'] == 'ok' &&
|
|
body['api_version'] == 1) {
|
|
return const ConnectionTestResult(
|
|
isAvailable: true,
|
|
message: 'Conexão com o servidor estabelecida.',
|
|
);
|
|
}
|
|
|
|
return const ConnectionTestResult(
|
|
isAvailable: false,
|
|
message: 'O servidor não confirmou a disponibilidade da API PDV.',
|
|
);
|
|
} on TimeoutException {
|
|
return const ConnectionTestResult(
|
|
isAvailable: false,
|
|
message: 'Tempo esgotado ao conectar ao servidor.',
|
|
);
|
|
} on SocketException {
|
|
return const ConnectionTestResult(
|
|
isAvailable: false,
|
|
message: 'Não foi possível alcançar o servidor.',
|
|
);
|
|
} on FormatException {
|
|
return const ConnectionTestResult(
|
|
isAvailable: false,
|
|
message: 'O servidor retornou uma resposta inválida.',
|
|
);
|
|
} catch (_) {
|
|
return const ConnectionTestResult(
|
|
isAvailable: false,
|
|
message: 'Não foi possível testar a conexão com o servidor.',
|
|
);
|
|
}
|
|
}
|
|
}
|