Skip to content

Commit

Permalink
Merge pull request #12 from RooftopAcademy/15-10-2021
Browse files Browse the repository at this point in the history
15 - 10 - 2021 / Users
  • Loading branch information
ChachoPacho authored Oct 19, 2021
2 parents 813d612 + f8ca37c commit 1f52f80
Show file tree
Hide file tree
Showing 72 changed files with 1,115 additions and 166 deletions.
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/js/
/node_modules/
node_modules/
build/
public/js/
23 changes: 14 additions & 9 deletions app/client/class/API.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,30 @@ import apiErrorHandler from "../errors/apiErrorHandler";
export default abstract class API {
public static async fetchAPI(
url: string,
data?: object
): Promise<Product[] | apiError | Product> {
return await fetch(url, {
method: "POST",
data?: object,
method: string = "POST"
): Promise<any | apiError> {
const response = await fetch(url, {
method,
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data)
})
.then((e) => e.json())
.then((res) => (Object.keys(res).length === 0 ? API_ERROR : res));
body: JSON.stringify(data),
});
const responseJson = await response.json();

if (response.ok) {
return Object.keys(responseJson).length === 0 ? API_ERROR : responseJson;
}
return (responseJson as any).message;
}

/**
*
* @param apiResponse An API method return
* @returns if the api is or not an Error
*/
public static isApiError(apiResponse: Product[] | apiError | Product): boolean {
public static isApiError(apiResponse: any | apiError): boolean {
if (typeof apiResponse === "string") {
apiErrorHandler("Ha ocurrido un error.");
return true;
Expand Down
12 changes: 12 additions & 0 deletions app/client/class/App.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,35 @@ import shopListener from "../listeners/shopListener";

// CLASSES
import Favorites from "./Favorites";
import Users from "./Users";
import Cart from "./Cart";
import UI from "./UI";

// SCRIPTS
import updateQuantityProducts from "../scripts/updateQuantityProducts";
import loadTable from "../scripts/loadTable";
import { CURRENT_PAGE } from "../config";
import loginRegisterListener from "../listeners/loginRegisterListener";

export default class App {
public ui: UI;
public cart: Cart;
public users: Users;
public favorites: Favorites;
private PREPARE: {
[index: string]: string;
} = {
products: "productsPrepare",
product: "productPrepare",
cart: "cartPrepare",
users: "usersPrepare"
};

constructor(HTML_APP: HTMLElement) {
this.ui = new UI(HTML_APP);
this.cart = new Cart();
this.favorites = new Favorites();
this.users = new Users();
}

/**
Expand Down Expand Up @@ -70,4 +75,11 @@ export default class App {
closeCartListener(this.cart);
loadTable(this.cart);
}

/**
* Loads all listeners for Users.
*/
private usersPrepare(): void {
loginRegisterListener();
}
}
2 changes: 1 addition & 1 deletion app/client/class/Cart.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import CartStructure from "../interfaces/CartStructure";
import CartProduct from "../interfaces/CartProduct";

import { cartProductsList } from "../types/cart";

import Storage from "./Storage";

import { SS_CART } from "../config";
import cartErrorHandler from "../errors/cartErrorHandler";
import CartProduct from "../interfaces/CartProduct";

export default class Cart extends Storage<CartStructure> {
private products: any = [];
Expand Down
2 changes: 1 addition & 1 deletion app/client/class/Router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export default class Router {
return (
"?" +
Object.keys(params)
.map((key) => `${key}=params[key]`)
.map((key) => `${key}=${params[key]}`)
.join("&")
);
}
Expand Down
43 changes: 43 additions & 0 deletions app/client/class/Users.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import User from "../interfaces/User";

import API from "./API";
import Router from "./Router";
import Storage from "./Storage";

export default class Users extends Storage<User> {
constructor() {
super("user", {
id: null,
email: "",
password: "",
});
}

public async loginUser(email: string, password: string): Promise<void | string> {
const response = await API.fetchAPI(Router.createURL("/users"), { email, password });
if (API.isApiError(response)) {
return response.message
}
this.updateStorage({
id: response.id,
email,
password
})
}

public async registerUser(email: string, password: string): Promise<void | string> {
const response = await API.fetchAPI(Router.createURL("/users"), { email, password }, "PUT");
if (API.isApiError(response)) {
return response.message
}
this.updateStorage({
id: response.id,
email,
password
})
}

public isLogued(): boolean {
return !!this.getStorage().id;
}
}
17 changes: 17 additions & 0 deletions app/client/handlers/loginHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import app from "../main";

// HTML
const LOGIN_FORM: HTMLFormElement = document.getElementById(
"js-loginForm"
) as HTMLFormElement;

export default async function loginHandler(): Promise<void> {
const { email, password } = Object.fromEntries(
new FormData(LOGIN_FORM).entries()
) as {
[index: string]: string;
};
const response = await app.users.loginUser(email, password);

return alert(response ? response : "Logueado con Éxito");
}
20 changes: 20 additions & 0 deletions app/client/handlers/registerHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import app from "../main";

// HTML
const REGISTER_FORM: HTMLFormElement = document.getElementById(
"js-registerForm"
) as HTMLFormElement;

export default async function registerHandler(): Promise<void> {
const { email, password, passwordRepeat } = Object.fromEntries(
new FormData(REGISTER_FORM).entries()
) as { [index: string]: string };

if (password === passwordRepeat) {
const response = await app.users.registerUser(email, password);

return alert(response ? response : "Registrado con Éxito");
}

alert("Las contraseñas no coinciden.");
}
5 changes: 5 additions & 0 deletions app/client/interfaces/User.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default interface User {
id: number,
email: string,
password: string
}
3 changes: 3 additions & 0 deletions app/client/listeners/favoritesListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ const SEARCH_INPUT_S_EVENT: string = "keyup";
export default function favoritesListener(): void {
Array.from(FAVORITES_ICONS).forEach((favorites_icon: Element): void => {
favorites_icon.addEventListener(SEARCH_INPUT_S_EVENT, (e) => {
if (!app.users.isLogued()) {
return alert("Necesitas estar Logueado!");
}
const productID: number = +(favorites_icon as HTMLElement).dataset.id;
app.favorites.handleFavorite(productID);
});
Expand Down
15 changes: 15 additions & 0 deletions app/client/listeners/loginRegisterListener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import loginHandler from "../handlers/loginHandler";
import registerHandler from "../handlers/registerHandler";

// HTML
const LOGIN_FORM_BTN: HTMLElement = document.getElementById("js-loginFormBTN");
const REGISTER_FORM: HTMLElement = document.getElementById("js-registerForm");

// EVENTS
const REGISTER_FORM_BTN_EVENT: string = "click";
const LOGIN_FORM_BTN_EVENT: string = "click";

export default function loginRegisterListener(): void {
LOGIN_FORM_BTN.addEventListener(LOGIN_FORM_BTN_EVENT, loginHandler);
REGISTER_FORM.addEventListener(REGISTER_FORM_BTN_EVENT, registerHandler);
}
3 changes: 2 additions & 1 deletion app/client/scripts/sendSearchRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ export default function sendSearchRequest(
input: HTMLInputElement
): void {
//if (CURRENT_PAGE !== "products") {
console.log(input.value)
return Router.followWithParams("/products", {
"search": input.value
search: input.value
})
//}
}
43 changes: 0 additions & 43 deletions app/server/classes/API.ts

This file was deleted.

47 changes: 47 additions & 0 deletions app/server/classes/DataBase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import Filter from "./Filter";

const fs = require("fs");

const { DATABASE_DIR } = require("../config");

export default class DataBase extends Filter {
private table: string;
private readonly tableNames = ["config", "products", "users", "favorites"];

constructor(tableName: string) {
super();
this.table = this.returnTable(tableName);
}

protected getTable(): any {
return this.table;
}

protected setTable(tableName: string, tableData: any): void {
fs.writeFileSync(this.getTablePath(tableName), JSON.stringify(tableData));
}

protected returnTable(tableName: string): any {
if (this.tableNames.includes(tableName)) {
return JSON.parse(fs.readFileSync(this.getTablePath(tableName), "utf8"));
}
}

protected getConfig(configEntry: string): any {
return this.returnConfig()[configEntry];
}

protected setConfig(configEntry: string, configData: any): void {
const config = this.returnConfig();
config[configEntry] = configData;
this.setTable("config", config);
}

private getTablePath(tableName: string): string {
return `${DATABASE_DIR}/${tableName}.json`;
}

private returnConfig(): any {
return this.returnTable("config");
}
}
9 changes: 9 additions & 0 deletions app/server/classes/Filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default class Filter {
protected inRange(
elem: number,
min: number = null,
max: number = null
): boolean {
return (min ? elem >= min : true) && (max ? elem <= max : true);
}
}
Loading

0 comments on commit 1f52f80

Please sign in to comment.