base_service.dart 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import '../data/session/session_storage.dart';
  4. import 'package:http/http.dart' as http;
  5. class BaseService {
  6. int currentPage = 0;
  7. int limit = 20;
  8. int total = 0;
  9. String base_url = 'https://dev.computosonora.com';
  10. String baseUrl = 'dev.computosonora.com';
  11. Future<Map<String, String>> getDefaultHeaders({withAuth = true}) async {
  12. Map<String, String> defaultHeaders = {'Content-Type': 'application/json'};
  13. if (withAuth) {
  14. String? token = await SessionStorage().getToken();
  15. defaultHeaders['Authorization'] = 'Bearer ${token ?? ''}';
  16. }
  17. return defaultHeaders;
  18. }
  19. Future<http.Response> get(String endpoint,
  20. {bool withAuth = true,
  21. Map<String, String>? queryParameters,
  22. Map<String, String>? headers}) async {
  23. final uri = Uri.https(baseUrl, endpoint, queryParameters);
  24. var defaultHeaders = await getDefaultHeaders(withAuth: withAuth);
  25. var head = {...?headers, ...defaultHeaders};
  26. return await http.get(uri, headers: head);
  27. }
  28. Map<String, String> getHeader(String token) => {
  29. 'Authorization': 'Bearer ' + token,
  30. 'Accept': 'application/json',
  31. 'Content-Type': 'application/json',
  32. };
  33. Future<http.Response?> getHttp(String url, String token) async {
  34. try {
  35. return await http
  36. .get(Uri.parse(base_url + url), headers: getHeader(token))
  37. .timeout(Duration(seconds: 120));
  38. } on TimeoutException catch (e) {
  39. print(e);
  40. return null;
  41. }
  42. }
  43. Future<http.Response> post(String endpoint,
  44. {bool withAuth = true,
  45. Map<String, String>? queryParameters,
  46. Map<String, dynamic>? body,
  47. Map<String, String>? headers}) async {
  48. final uri = Uri.https(baseUrl, endpoint, queryParameters);
  49. var defaultHeaders = await getDefaultHeaders(withAuth: withAuth);
  50. var head = {...?headers, ...defaultHeaders};
  51. return await http.post(uri, body: json.encode(body), headers: head);
  52. }
  53. Future<http.Response> delete(String endpoint,
  54. {bool withAuth = true,
  55. Map<String, String>? queryParameters,
  56. Map<String, dynamic>? body,
  57. Map<String, String>? headers}) async {
  58. final uri = Uri.https(baseUrl, endpoint, queryParameters);
  59. var defaultHeaders = await getDefaultHeaders(withAuth: withAuth);
  60. var head = {...?headers, ...defaultHeaders};
  61. return await http.delete(uri, body: json.encode(body), headers: head);
  62. }
  63. }