feat: add ApiService for HTTP POST

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Misaka
2026-05-07 19:54:22 +08:00
parent 2693c13133
commit ef4dd51fc1
2 changed files with 65 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiService {
final http.Client _client;
ApiService({http.Client? client}) : _client = client ?? http.Client();
Future<bool> sendScanData(
String url, {
required String barcode,
required String codeType,
}) async {
try {
final response = await _client
.post(
Uri.parse(url),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'barcode': barcode,
'code_type': codeType,
'timestamp': DateTime.now().toUtc().toIso8601String(),
}),
)
.timeout(const Duration(seconds: 5));
return response.statusCode >= 200 && response.statusCode < 300;
} catch (_) {
return false;
}
}
}

View File

@@ -0,0 +1,34 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:pad_scanner/services/api_service.dart';
void main() {
group('ApiService', () {
test('sendScanData returns true on 200', () async {
final client = MockClient((request) async {
return http.Response('{"status":"ok"}', 200);
});
final service = ApiService(client: client);
final result = await service.sendScanData(
'http://localhost:8000/scan',
barcode: '123456',
codeType: 'CODE128',
);
expect(result, isTrue);
});
test('sendScanData returns false on error', () async {
final client = MockClient((request) async {
return http.Response('error', 500);
});
final service = ApiService(client: client);
final result = await service.sendScanData(
'http://localhost:8000/scan',
barcode: '123456',
codeType: 'CODE128',
);
expect(result, isFalse);
});
});
}