articles_api.dart 1.76 KB
Newer Older
yenisleydi committed
1 2 3
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:primer_practica/environments/urls.dart' as api;
yenisleydi committed
4
import 'dart:convert';
yenisleydi committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

class ArticlesApi {
  Future<Map<String, dynamic>> getArticles() async {
    String url = '${api.apiApp}/articulo?offset=0&max=100';

    if (kDebugMode) {
      print('Url -> $url');
    }

    try {
      final resp = await http.get(Uri.parse(url));
      return {"statusCode": resp.statusCode, "body": resp.body};
    } catch (e) {
      return {"statusCode": 501, "body": '$e'};
    }
  }
yenisleydi committed
21 22

  Future<Map<String, dynamic>> searchArticles(String query) async {
yenisleydi committed
23
    String url = '${api.apiApp}/articulo?nombre="$query"';
yenisleydi committed
24 25 26 27 28 29 30 31 32 33 34 35

    if (kDebugMode) {
      print('Url -> $url');
    }

    try {
      final resp = await http.get(Uri.parse(url));
      return {"statusCode": resp.statusCode, "body": resp.body};
    } catch (e) {
      return {"statusCode": 501, "body": '$e'};
    }
  }
yenisleydi committed
36 37 38 39 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<Map<String, dynamic>> addArticle({
    required String clave,
    required int categoria,
    required String nombre,
    required List<double> precios,
    required bool activo,
  }) async {
    String url = '${api.apiApp}/articulo';
    final payload = {
      'clave': clave,
      'categoria': categoria,
      'nombre': nombre,
      'precios': precios.map((precio) => {'precio': precio}).toList(),
      'activo': activo,
    };

    if (kDebugMode) {
      print('Url -> $url');
      print('Payload -> $payload');
    }

    try {
      final resp = await http.post(
        Uri.parse(url),
        headers: {'Content-Type': 'application/json'},
        body: json.encode(payload),
      );
      return {"statusCode": resp.statusCode, "body": resp.body};
    } catch (e) {
      return {"statusCode": 501, "body": '$e'};
    }
  }
yenisleydi committed
69
}