Refactor(api_service): streamline API request handling and normalize data types
- Updated the `createUser` method for improved readability and consistency. - Refactored normalization functions to return specific enum types for categories, severities, and statuses. - Adjusted the handling of image uploads and location data to enhance clarity and maintainability. - Changed the dependency type for the `http` package in `pubspec.lock` to reflect its direct usage.
This commit is contained in:
@@ -1,9 +1,8 @@
|
|||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'dart:io';
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
import 'package:uuid/uuid.dart';
|
import 'package:uuid/uuid.dart';
|
||||||
import '../models/report.dart';
|
import '../models/report.dart';
|
||||||
|
import '../models/enums.dart';
|
||||||
|
|
||||||
/// Service for communicating with the FixMate Backend API
|
/// Service for communicating with the FixMate Backend API
|
||||||
class ApiService {
|
class ApiService {
|
||||||
@@ -19,15 +18,15 @@ class ApiService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Create a new user
|
/// Create a new user
|
||||||
static Future<String> createUser({required String name, required String email}) async {
|
static Future<String> createUser({
|
||||||
|
required String name,
|
||||||
|
required String email,
|
||||||
|
}) async {
|
||||||
try {
|
try {
|
||||||
final response = await http.post(
|
final response = await http.post(
|
||||||
Uri.parse('$_baseUrl/users'),
|
Uri.parse('$_baseUrl/users'),
|
||||||
headers: {'Content-Type': 'application/json'},
|
headers: {'Content-Type': 'application/json'},
|
||||||
body: json.encode({
|
body: json.encode({'name': name, 'email': email}),
|
||||||
'name': name,
|
|
||||||
'email': email,
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
if (response.statusCode == 200) {
|
if (response.statusCode == 200) {
|
||||||
@@ -53,7 +52,10 @@ class ApiService {
|
|||||||
try {
|
try {
|
||||||
final userId = await _getOrCreateUserId();
|
final userId = await _getOrCreateUserId();
|
||||||
|
|
||||||
var request = http.MultipartRequest('POST', Uri.parse('$_baseUrl/report'));
|
var request = http.MultipartRequest(
|
||||||
|
'POST',
|
||||||
|
Uri.parse('$_baseUrl/report'),
|
||||||
|
);
|
||||||
request.fields['user_id'] = userId;
|
request.fields['user_id'] = userId;
|
||||||
request.fields['latitude'] = latitude.toString();
|
request.fields['latitude'] = latitude.toString();
|
||||||
request.fields['longitude'] = longitude.toString();
|
request.fields['longitude'] = longitude.toString();
|
||||||
@@ -61,11 +63,7 @@ class ApiService {
|
|||||||
|
|
||||||
// Add the image file
|
// Add the image file
|
||||||
request.files.add(
|
request.files.add(
|
||||||
http.MultipartFile.fromBytes(
|
http.MultipartFile.fromBytes('image', imageBytes, filename: imageName),
|
||||||
'image',
|
|
||||||
imageBytes,
|
|
||||||
filename: imageName,
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
final response = await request.send();
|
final response = await request.send();
|
||||||
@@ -156,62 +154,72 @@ class ApiService {
|
|||||||
category: _normalizeCategory(data['category'] ?? ''),
|
category: _normalizeCategory(data['category'] ?? ''),
|
||||||
severity: _normalizeSeverity(data['severity'] ?? 'N/A'),
|
severity: _normalizeSeverity(data['severity'] ?? 'N/A'),
|
||||||
status: _normalizeStatus(data['status'] ?? 'New'),
|
status: _normalizeStatus(data['status'] ?? 'New'),
|
||||||
description: data['description'] ?? '',
|
photoPath: data['image_path'] != null
|
||||||
latitude: data['latitude']?.toDouble() ?? 0.0,
|
? '$_uploadsUrl/${data['image_path'].split('/').last}'
|
||||||
longitude: data['longitude']?.toDouble() ?? 0.0,
|
: null,
|
||||||
createdAt: DateTime.parse(data['created_at'] ?? DateTime.now().toIso8601String()),
|
location: LocationData(
|
||||||
updatedAt: DateTime.parse(data['updated_at'] ?? DateTime.now().toIso8601String()),
|
lat: (data['latitude'] as num?)?.toDouble() ?? 0.0,
|
||||||
// Image path will be constructed from the API response
|
lng: (data['longitude'] as num?)?.toDouble() ?? 0.0,
|
||||||
imagePath: data['image_path'] != null ? '$_uploadsUrl/${data['image_path'].split('/').last}' : null,
|
),
|
||||||
|
createdAt: data['created_at'] ?? DateTime.now().toIso8601String(),
|
||||||
|
updatedAt: data['updated_at'] ?? DateTime.now().toIso8601String(),
|
||||||
|
deviceId: 'api-${data['ticket_id'] ?? ''}',
|
||||||
|
notes: data['description'] as String?,
|
||||||
|
source: 'api',
|
||||||
|
aiSuggestion: AISuggestion(
|
||||||
|
category: _normalizeCategory(data['category'] ?? ''),
|
||||||
|
severity: _normalizeSeverity(data['severity'] ?? 'N/A'),
|
||||||
|
confidence: 0.8, // Default confidence since we don't get this from API
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Normalize category names to match the app's expected format
|
/// Normalize category names to match the app's expected format
|
||||||
static String _normalizeCategory(String category) {
|
static Category _normalizeCategory(String category) {
|
||||||
// Convert API categories to app categories
|
// Convert API categories to app categories
|
||||||
switch (category.toLowerCase()) {
|
switch (category.toLowerCase()) {
|
||||||
case 'pothole':
|
case 'pothole':
|
||||||
return 'pothole';
|
return Category.pothole;
|
||||||
case 'streetlight':
|
case 'streetlight':
|
||||||
case 'broken_streetlight':
|
case 'broken_streetlight':
|
||||||
return 'streetlight';
|
return Category.streetlight;
|
||||||
case 'garbage':
|
case 'garbage':
|
||||||
return 'trash';
|
return Category.trash;
|
||||||
case 'signage':
|
case 'signage':
|
||||||
return 'signage';
|
return Category.signage;
|
||||||
case 'drainage':
|
case 'drainage':
|
||||||
return 'drainage';
|
return Category.drainage;
|
||||||
default:
|
default:
|
||||||
return 'other';
|
return Category.other;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Normalize severity levels
|
/// Normalize severity levels
|
||||||
static String _normalizeSeverity(String severity) {
|
static Severity _normalizeSeverity(String severity) {
|
||||||
switch (severity.toLowerCase()) {
|
switch (severity.toLowerCase()) {
|
||||||
case 'high':
|
case 'high':
|
||||||
return 'high';
|
return Severity.high;
|
||||||
case 'medium':
|
case 'medium':
|
||||||
return 'medium';
|
return Severity.medium;
|
||||||
case 'low':
|
case 'low':
|
||||||
return 'low';
|
return Severity.low;
|
||||||
default:
|
default:
|
||||||
return 'low'; // Default to low if unknown
|
return Severity.low; // Default to low if unknown
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Normalize status values
|
/// Normalize status values
|
||||||
static String _normalizeStatus(String status) {
|
static Status _normalizeStatus(String status) {
|
||||||
switch (status.toLowerCase()) {
|
switch (status.toLowerCase()) {
|
||||||
case 'new':
|
case 'new':
|
||||||
return 'submitted';
|
return Status.submitted;
|
||||||
case 'in progress':
|
case 'in progress':
|
||||||
case 'in_progress':
|
case 'in_progress':
|
||||||
return 'in_progress';
|
return Status.inProgress;
|
||||||
case 'fixed':
|
case 'fixed':
|
||||||
return 'fixed';
|
return Status.fixed;
|
||||||
default:
|
default:
|
||||||
return 'submitted';
|
return Status.submitted;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -262,7 +262,7 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "0.2.5"
|
version: "0.2.5"
|
||||||
http:
|
http:
|
||||||
dependency: transitive
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: http
|
name: http
|
||||||
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
|
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
|
||||||
|
|||||||
Reference in New Issue
Block a user