|
|
@@ -1,31 +1,52 @@
|
|
|
import { Dispatch } from "react";
|
|
|
import { Action } from "./actionTypes";
|
|
|
+import { login as apiLoginRequest } from "../../api";
|
|
|
|
|
|
-export const loginRequest = (username: string, password: string) => async (
|
|
|
+export const login = (username: string, password: string) => async (
|
|
|
dispatch: Dispatch<Action>
|
|
|
) => {
|
|
|
- // Request
|
|
|
- const res = await fetch(`${process.env.BACKEND_BASE_URL}/login`, {});
|
|
|
+ // Loading login state
|
|
|
+ dispatch(loginRequest());
|
|
|
|
|
|
- // TODO: get user token
|
|
|
- const userToken = "";
|
|
|
+ const errors = {
|
|
|
+ 400: "Credenciales inválidas",
|
|
|
+ };
|
|
|
+
|
|
|
+ try {
|
|
|
+ const res = await apiLoginRequest(username, password);
|
|
|
+ if (!res.ok) {
|
|
|
+ const msg = (errors as any)[res.status];
|
|
|
+ dispatch(loginFailure(msg ?? "Request inválida"));
|
|
|
+ const text = await res.text();
|
|
|
+ console.log("Error en el login", text);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ const body = await res.json();
|
|
|
+
|
|
|
+ const userToken = body.token;
|
|
|
|
|
|
- // Handle request
|
|
|
- if (res.ok) {
|
|
|
dispatch(loginSuccess(username, userToken));
|
|
|
- return;
|
|
|
+ } catch (e) {
|
|
|
+ console.error(e);
|
|
|
+ dispatch(loginFailure("Error de conexión"));
|
|
|
}
|
|
|
-
|
|
|
- const code = res.status;
|
|
|
- dispatch(loginFailure(code));
|
|
|
};
|
|
|
|
|
|
+export const loginRequest = (): Action => ({
|
|
|
+ type: "LOGIN_REQUEST",
|
|
|
+});
|
|
|
+
|
|
|
export const loginSuccess = (username: string, userToken: string): Action => ({
|
|
|
type: "LOGIN_SUCCESS",
|
|
|
username,
|
|
|
userToken,
|
|
|
});
|
|
|
-export const loginFailure = (code: number): Action => ({
|
|
|
+export const loginFailure = (code: string): Action => ({
|
|
|
type: "LOGIN_FAILURE",
|
|
|
error: code,
|
|
|
});
|
|
|
+
|
|
|
+export const failureDismiss = (): Action => ({
|
|
|
+ type: "LOGIN_FAILURE_DISMISS",
|
|
|
+});
|