56 lines
1.7 KiB
Dart
56 lines
1.7 KiB
Dart
import 'dart:convert';
|
|
import 'package:http/http.dart' as http;
|
|
import '../config/api_config.dart';
|
|
import '../models/conversation.dart';
|
|
import '../models/message.dart';
|
|
|
|
class ApiService {
|
|
String? _token;
|
|
|
|
void setToken(String? token) {
|
|
_token = token;
|
|
}
|
|
|
|
Map<String, String> get _headers => {
|
|
'Content-Type': 'application/json',
|
|
if (_token != null) 'Authorization': 'Bearer $_token',
|
|
};
|
|
|
|
Future<List<Conversation>> getConversations() async {
|
|
final response = await http.get(
|
|
Uri.parse('${ApiConfig.baseUrl}/conversations'),
|
|
headers: _headers,
|
|
).timeout(ApiConfig.connectionTimeout);
|
|
|
|
if (response.statusCode == 200) {
|
|
final List<dynamic> data = jsonDecode(response.body);
|
|
return data.map((e) => Conversation.fromJson(e)).toList();
|
|
}
|
|
throw Exception('Failed to load conversations');
|
|
}
|
|
|
|
Future<List<Message>> getConversationMessages(String conversationId) async {
|
|
final response = await http.get(
|
|
Uri.parse('${ApiConfig.baseUrl}/conversations/$conversationId'),
|
|
headers: _headers,
|
|
).timeout(ApiConfig.connectionTimeout);
|
|
|
|
if (response.statusCode == 200) {
|
|
final List<dynamic> data = jsonDecode(response.body);
|
|
return data.map((e) => Message.fromJson(e)).toList();
|
|
}
|
|
throw Exception('Failed to load messages');
|
|
}
|
|
|
|
Future<void> deleteConversation(String conversationId) async {
|
|
final response = await http.delete(
|
|
Uri.parse('${ApiConfig.baseUrl}/conversations/$conversationId'),
|
|
headers: _headers,
|
|
).timeout(ApiConfig.connectionTimeout);
|
|
|
|
if (response.statusCode != 200) {
|
|
throw Exception('Failed to delete conversation');
|
|
}
|
|
}
|
|
}
|