Ver Fonte

Generalizacion mustFetchJson y listar estaciones

wilitp há 4 anos atrás
pai
commit
060a7d4635
1 ficheiros alterados com 22 adições e 22 exclusões
  1. 22 22
      app/src/api/tables.ts

+ 22 - 22
app/src/api/tables.ts

@@ -1,9 +1,25 @@
 import { apiURL } from "../config";
-import { Summary } from "../types/summary";
+import { Summary, Station } from "../types";
 import { mockPayloads, mockRequest } from "./mocks";
 // Quizas llamarlos table no hacia falta,
 // pero es preferible antes de que a alguien se le olvide usar un alias cuando importe estas funciones.
 
+const mustFetchJson = <T>(url: string, config: RequestInit) =>
+  new Promise<T>(async (resolve, reject) => {
+    const res = await fetch(url, config);
+    if (!res.ok) {
+      const reason = await res.text();
+      reject(reason);
+    }
+
+    try {
+      const body = await res.json();
+      resolve(body);
+    } catch (err) {
+      reject(err);
+    }
+  });
+
 export const generalTable = (from: string, to: string, token: string) => {
   const headers = new Headers();
   headers.append("Access-Control-Allow-Origin", "*");
@@ -18,26 +34,10 @@ export const generalTable = (from: string, to: string, token: string) => {
   const qParams = new URLSearchParams();
   qParams.append("start_datetime", from);
   qParams.append("end_datetime", to);
-
-  console.log({ from, to });
-
-  return new Promise<Summary[]>(async (resolve, reject) => {
-    const res = await fetch(
-      `${apiURL}summary/all_stations?${qParams.toString()}`,
-      config
-    );
-    if (!res.ok) {
-      const reason = await res.text();
-      reject(reason);
-    }
-
-    try {
-      const body = await res.json();
-      resolve(body);
-    } catch (err) {
-      reject(err);
-    }
-  });
+  return mustFetchJson<Summary[]>(
+    `${apiURL}summary/all_stations?${qParams.toString()}`,
+    config
+  );
 };
 
 export const seasonsSummariesTable = (
@@ -58,5 +58,5 @@ export const sectors = (token: string) => {
     mode: "cors",
     headers,
   };
-  return fetch(`${apiURL}fincas`, config);
+  return mustFetchJson<Station[]>(`${apiURL}fincas`, config);
 };