articles_controller.dart 2.4 KB
Newer Older
yenisleydi committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
import 'dart:convert';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:primer_practica/src/models/articles_model.dart';
import '../http_api/articles_api.dart';

class ArticleController {
  final Connectivity _connectivity = Connectivity();
  final ArticlesApi _articleApi = ArticlesApi();

  Future<Map<String, dynamic>> getArticles(int categoryId) async {
    Map<String, dynamic> mapResp = {
      'ok': false,
      'message': 'No hay artículos',
      'data': null
    };

    ConnectivityResult connectivityResult = await _connectivity.checkConnectivity();
    if (connectivityResult != ConnectivityResult.none) {
      if (connectivityResult == ConnectivityResult.wifi || connectivityResult == ConnectivityResult.mobile) {
        Map<String, dynamic> respGet = await _articleApi.getArticles();

        if (respGet['statusCode'] == 200) {
          try {
            var decodeResp = json.decode(respGet['body']);
            List<ArticlesModel> listArticles = ArticlesModel.fromJsonArray(decodeResp['data']);
            mapResp['ok'] = true;
            mapResp['message'] = "${listArticles.length} artículos encontrados";
            mapResp['data'] = listArticles;
          } catch (e) {
            mapResp['message'] = "Error en el procesamiento de datos: $e";
          }
        } else {
          mapResp['message'] = "${respGet['body']}";
        }
      }
    }

    return mapResp;
  }
yenisleydi committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

  Future<List<ArticlesModel>> searchArticles(String query) async {
    List<ArticlesModel> listArticles = [];

    ConnectivityResult connectivityResult = await _connectivity.checkConnectivity();
    if (connectivityResult != ConnectivityResult.none) {
      if (connectivityResult == ConnectivityResult.wifi || connectivityResult == ConnectivityResult.mobile) {
        Map<String, dynamic> respGet = await _articleApi.searchArticles(query);

        if (respGet['statusCode'] == 200) {
          try {
            var decodeResp = json.decode(respGet['body']);
            listArticles = ArticlesModel.fromJsonArray(decodeResp['data']);
          } catch (e) {
            throw Exception("Error en el procesamiento de datos: $e");
          }
        } else {
          throw Exception("Error en la respuesta de la API: ${respGet['body']}");
        }
      } else {
        throw Exception("No hay conectividad");
      }
    } else {
      throw Exception("No hay conectividad");
    }

    return listArticles;
  }
}