Chepuhagram/lib/data/repositories/contact_repository.dart

73 lines
2.1 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'dart:convert';
import 'package:http/http.dart' as http;
import '/core/constants.dart';
import '/data/models/contact_model.dart';
import '/domain/services/api_service.dart';
class ContactRepository {
final http.Client _client = http.Client();
final ApiService _apiService = ApiService();
Future<List<Contact>> fetchChatContacts() async {
final token = await _apiService.getAccessToken();
if (token == null) {
throw Exception('No access token');
}
final response = await _client.get(
Uri.parse('${AppConstants.baseUrl}/users/chats'),
headers: {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
},
);
if (response.statusCode == 200) {
final List<dynamic> data = jsonDecode(utf8.decode(response.bodyBytes));
return data.map((json) => Contact.fromJson(json)).toList();
} else {
throw Exception('Failed to load contacts');
}
}
Future<List<Contact>> fetchAllUsers() async {
final token = await _apiService.getAccessToken();
if (token == null) {
throw Exception('No access token');
}
final response = await _client.get(
Uri.parse('${AppConstants.baseUrl}/users/all'),
headers: {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
},
);
if (response.statusCode == 200) {
final List<dynamic> data = jsonDecode(utf8.decode(response.bodyBytes));
return data.map((json) => Contact.fromJson(json)).toList();
} else {
throw Exception('Failed to load contacts');
}
}
Future<Contact> fetchContactById(int userId) async {
final token = await _apiService.getAccessToken();
final response = await _client.get(
Uri.parse('${AppConstants.baseUrl}/users/$userId'),
headers: {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
},
);
if (response.statusCode == 200) {
final data = jsonDecode(utf8.decode(response.bodyBytes));
return Contact.fromJson(data);
} else {
throw Exception('Не удалось загрузить данные контакта');
}
}
}