From cbc742b25a8082a4c26eb58a8bd0884b5794bb8b Mon Sep 17 00:00:00 2001 From: Maxiwere45 Date: Tue, 9 Jun 2026 11:11:31 +0200 Subject: [PATCH] feat(data): add HTTP remote datasource Co-Authored-By: Claude Opus 4.8 --- .../pokemon_remote_datasource.dart | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 lib/data/datasources/pokemon_remote_datasource.dart diff --git a/lib/data/datasources/pokemon_remote_datasource.dart b/lib/data/datasources/pokemon_remote_datasource.dart new file mode 100644 index 0000000..de3a70a --- /dev/null +++ b/lib/data/datasources/pokemon_remote_datasource.dart @@ -0,0 +1,46 @@ +import 'dart:convert'; +import 'package:http/http.dart' as http; +import '../../core/config/app_constants.dart'; +import '../../core/logger.dart'; +import '../../domain/entities/pokemon.dart'; +import '../dto/pokemon_dto.dart'; + +/// Accès distant à l'API Tyradex. +class PokemonRemoteDataSource { + final http.Client _client; + + PokemonRemoteDataSource({http.Client? client}) + : _client = client ?? http.Client(); + + Future getById(int id) async { + AppLogger.info('API: fetching Pokémon $id'); + final response = await _client + .get(Uri.https(AppConstants.apiBaseUrl, '${AppConstants.apiPokemonPath}/$id')); + if (response.statusCode != 200) { + throw Exception( + 'Erreur récupération du pokémon $id, code ${response.statusCode}'); + } + final json = jsonDecode(response.body) as Map; + return PokemonDto.fromTyradexJson(json, fallbackId: id); + } + + Future> getAll() async { + AppLogger.info('API: fetching ALL Pokémon'); + final response = await _client + .get(Uri.https(AppConstants.apiBaseUrl, AppConstants.apiPokemonPath)); + if (response.statusCode != 200) { + throw Exception('Failed to load pokemon (code ${response.statusCode})'); + } + final List jsonList = jsonDecode(response.body); + final result = []; + for (final json in jsonList) { + if (json['pokedex_id'] == 0) continue; // entrée générique Tyradex + try { + result.add(PokemonDto.fromTyradexJson(json as Map)); + } catch (e, st) { + AppLogger.error('Parsing pokemon échoué: ${json['name']}', e, st); + } + } + return result; + } +}