1+ import 'dart:convert' ;
2+ import '../models/country.dart' ;
3+ import '../models/poster.dart' ;
4+ import '../models/media_item.dart' ;
5+ import 'base_repository.dart' ;
6+
7+ class CountriesRepository extends BaseRepository {
8+ static const String _countriesEndpoint = '/country/all' ;
9+ static const String _postersEndpoint = '/poster/by/filtres' ;
10+
11+ /// Fetch all countries from the API
12+ Future <List <CountryModel >> getCountries () async {
13+ try {
14+ final url = '${baseUrl }$_countriesEndpoint /${apiKey }/' ;
15+ final jsonData = await executeRequest (url);
16+ return parseCountries (jsonData);
17+ } catch (e) {
18+ throw Exception ('Error fetching countries: $e ' );
19+ }
20+ }
21+
22+ List <CountryModel > parseCountries (String jsonData) {
23+ final countries = < CountryModel > [];
24+ final jsonArray = json.decode (jsonData) as List ;
25+
26+ for (var item in jsonArray) {
27+ try {
28+ final countryObj = item as Map <String , dynamic >;
29+ final country = CountryModel .fromJson (countryObj);
30+ countries.add (country);
31+ } catch (e) {
32+ continue ;
33+ }
34+ }
35+
36+ return countries;
37+ }
38+
39+ /// Fetch posters by country ID
40+ Future <List <Poster >> getPostersByCountry (int countryId, {int page = 0 , FilterType filterType = FilterType .defaultFilter}) async {
41+ try {
42+ final url = '${baseUrl }$_postersEndpoint /0/$countryId /${filterType .apiValue }/$page /${apiKey }' ;
43+ final jsonData = await executeRequest (url);
44+ return parsePosters (jsonData);
45+ } catch (e) {
46+ throw Exception ('Error fetching posters for country $countryId : $e ' );
47+ }
48+ }
49+
50+ List <Poster > parsePosters (String jsonData) {
51+ final posters = < Poster > [];
52+ final jsonArray = json.decode (jsonData) as List ;
53+
54+ for (var item in jsonArray) {
55+ try {
56+ final posterObj = item as Map <String , dynamic >;
57+ final poster = Poster .fromJson (posterObj);
58+ posters.add (poster);
59+ } catch (e) {
60+ continue ;
61+ }
62+ }
63+
64+ return posters;
65+ }
66+ }
0 commit comments