Skip to content

Commit

Permalink
feat: leaderboard ippm
Browse files Browse the repository at this point in the history
  • Loading branch information
kaloslazo committed Nov 19, 2024
1 parent ec8cb3b commit 6ecc673
Show file tree
Hide file tree
Showing 5 changed files with 681 additions and 158 deletions.
186 changes: 97 additions & 89 deletions api/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,106 +2,114 @@ import { API_URL } from "@/constants";
import { AuthResponse, RegisterData, LoginData } from "@/types/auth";

export const authApi = {
register: async (data: RegisterData): Promise<AuthResponse> => {
console.log('Sending register request to:', `${API_URL}/auth/register`);
console.log('Register data:', { ...data, password: '***' });
register: async (data: RegisterData): Promise<AuthResponse> => {
console.log("Sending register request to:", `${API_URL}/auth/register`);
console.log("Register data:", { ...data, password: "***" });

try {
const response = await fetch(`${API_URL}/auth/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(data),
});
try {
const response = await fetch(`${API_URL}/auth/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(data),
credentials: "include", // Importante para manejar cookies
});

const responseData = await response.text();
console.log('Register raw response:', responseData);
// Primero verificamos si la respuesta es JSON válido
let responseData;
try {
responseData = await response.json();
} catch (e) {
throw new Error("El servidor no devolvió una respuesta JSON válida");
}

if (!response.ok) {
let errorMessage: string;
try {
const errorData = JSON.parse(responseData);
errorMessage = errorData.message || 'Error en el registro';
} catch (e) {
errorMessage = `Error en el registro: ${response.status} ${response.statusText}`;
}
throw new Error(errorMessage);
}
if (!response.ok) {
throw new Error(responseData.message || "Error en el registro");
}

try {
const parsedData = JSON.parse(responseData);
console.log('Register success:', parsedData);
return parsedData;
} catch (e) {
console.error('Error parsing success response:', e);
throw new Error('Error al procesar la respuesta del servidor');
}
} catch (error) {
console.error("Error registering user:", error);
throw error;
}
},
console.log("Register success:", responseData);
return responseData;
} catch (error) {
console.error("Error registering user:", error);
throw error instanceof Error
? error
: new Error("Error desconocido en el registro");
}
},

login: async (credentials: LoginData): Promise<AuthResponse> => {
try {
console.log('Login request:', { ...credentials, password: '***' });
login: async (credentials: LoginData): Promise<AuthResponse> => {
try {
console.log("Login request:", { ...credentials, password: "***" });

const response = await fetch(`${API_URL}/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(credentials),
});
const response = await fetch(`${API_URL}/auth/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(credentials),
credentials: "include", // Importante para manejar cookies
});

const responseData = await response.text();
console.log('Login response:', responseData);
// Primero verificamos si la respuesta es JSON válido
let responseData;
try {
responseData = await response.json();
} catch (e) {
throw new Error("El servidor no devolvió una respuesta JSON válida");
}

if (!response.ok) {
try {
const errorData = JSON.parse(responseData);
throw new Error(errorData.message || 'Error al iniciar sesión');
} catch (e) {
throw new Error('Error al iniciar sesión: ' + response.statusText);
}
}
if (!response.ok) {
throw new Error(
responseData.message ||
`Error al iniciar sesión: ${response.statusText}`
);
}

return JSON.parse(responseData);
} catch (error) {
console.error("Error logging in user:", error);
throw error;
}
},
return responseData;
} catch (error) {
console.error("Error logging in user:", error);
if (error instanceof Error) {
throw new Error(`Error al iniciar sesión: ${error.message}`);
}
throw new Error("Error desconocido al iniciar sesión");
}
},

verifyToken: async (token: string): Promise<AuthResponse> => {
try {
const response = await fetch(`${API_URL}/auth/verify`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json',
},
});
verifyToken: async (token: string): Promise<AuthResponse> => {
try {
const response = await fetch(`${API_URL}/auth/verify`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
},
credentials: "include", // Importante para manejar cookies
});

const responseData = await response.text();
console.log('Verify token response:', responseData);
// Primero verificamos si la respuesta es JSON válido
let responseData;
try {
responseData = await response.json();
} catch (e) {
throw new Error("El servidor no devolvió una respuesta JSON válida");
}

if (!response.ok) {
try {
const errorData = JSON.parse(responseData);
throw new Error(errorData.message || 'Token inválido');
} catch (e) {
throw new Error('Error al verificar token: ' + response.statusText);
}
}
if (!response.ok) {
throw new Error(
responseData.message || `Token inválido: ${response.statusText}`
);
}

return JSON.parse(responseData);
} catch (error) {
console.error("Error verifying token:", error);
throw error;
}
},
return responseData;
} catch (error) {
console.error("Error verifying token:", error);
if (error instanceof Error) {
throw new Error(`Error al verificar token: ${error.message}`);
}
throw new Error("Error desconocido al verificar token");
}
},
};
42 changes: 33 additions & 9 deletions api/complaints.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { ComplaintPointInterface } from "@/types";
import { API_URL } from "@/constants";

interface LeaderboardUser {
complaintsCount: number;
userDni: string;
userName: string;
}

export const complaintsApi = {
getAll: async (): Promise<ComplaintPointInterface[]> => {
try {
Expand All @@ -20,37 +26,36 @@ export const complaintsApi = {
create: async (formData: FormData): Promise<any> => {
try {
const response = await fetch(`${API_URL}/complaints`, {
method: 'POST',
method: "POST",
headers: {
'Accept': 'application/json',
Accept: "application/json",
},
body: formData
body: formData,
});

if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || response.statusText);
}

return await response.json();
} catch (error) {
console.error("Error creating complaint:", error);
throw error;
}
},


findOne: async (id: string): Promise<ComplaintPointInterface> => {
try {
const response = await fetch(`${API_URL}/complaints/${id}`);
const data = await response.json();

if (!response.ok) {
throw new Error(data.message || 'Error fetching complaint');
throw new Error(data.message || "Error fetching complaint");
}

if (!data) {
throw new Error('Complaint not found');
throw new Error("Complaint not found");
}

return data;
Expand All @@ -59,4 +64,23 @@ export const complaintsApi = {
throw error;
}
},
};

getLeaderboard: async (): Promise<LeaderboardUser[]> => {
try {
console.log("Fetching leaderboard from:", `${API_URL}/leaderboard`);
const response = await fetch(`${API_URL}/leaderboard`);

if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || "Error al obtener el ranking");
}

const data = await response.json();
console.log("Leaderboard data:", data);
return data || [];
} catch (error) {
console.error("Error fetching leaderboard:", error);
throw error;
}
},
};
Loading

0 comments on commit 6ecc673

Please sign in to comment.