Skip to content

Commit

Permalink
feat: add databases logic
Browse files Browse the repository at this point in the history
  • Loading branch information
joxpulp committed Sep 22, 2021
1 parent 9c399c9 commit af885d6
Show file tree
Hide file tree
Showing 25 changed files with 667 additions and 171 deletions.
18 changes: 0 additions & 18 deletions db/migrations/20210902034447_init.js

This file was deleted.

27 changes: 27 additions & 0 deletions db/migrations/20210902034447_init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Knex } from 'knex';

export async function up(knex: Knex) {
return knex.schema
.createTable('productos', (productsTable) => {
productsTable.increments();
productsTable.string('title').notNullable();
productsTable.string('description').notNullable();
productsTable.string('code').notNullable;
productsTable.decimal('price', 5, 2);
productsTable.string('thumbnail').notNullable();
productsTable.integer('stock');
})
.createTable('carrito', (cartTable) => {
cartTable.increments();
cartTable.string('title').notNullable();
cartTable.string('description').notNullable();
cartTable.string('code').notNullable;
cartTable.decimal('price', 5, 2);
cartTable.string('thumbnail').notNullable();
cartTable.integer('stock');
});
}

export async function down(knex: Knex) {
return knex.schema.dropTable('productos').dropTable('carrito');
}
Binary file renamed productos → e-commerce
Binary file not shown.
28 changes: 28 additions & 0 deletions src/apis/cartapi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { CartFactoryDAO } from '../models/cart/cartfactory';
import { Cart, Products } from '../models/interfaces';

const tipo = 2;

class CartAPI {
private cart;

constructor() {
this.cart = CartFactoryDAO.get(tipo);
}

async getProducts(id?: string): Promise<Cart[] | Products[]> {
if (id) return await this.cart.get(id);
return await this.cart.get();
}

async addProduct(id: string): Promise<Products[]> {
const newProduct = await this.cart.add(id);
return newProduct;
}

async deleteProduct(id: string) {
return await this.cart.delete(id);
}
}

export const cartAPI = new CartAPI();
8 changes: 4 additions & 4 deletions src/apis/productsapi.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { FactoryDAO } from '../models/products/productfactory';
import { Products, newProductI, ProductQuery } from '../models/interfaces';

const tipo = 6;
const tipo = 2;

class prodAPI {
private products;
Expand Down Expand Up @@ -34,9 +34,9 @@ class prodAPI {
return await this.products.delete(id);
}

// async query(options: ProductQuery) {
// return await this.products.query(options);
// }
async query(options: ProductQuery) {
return await this.products.query(options);
}
}

export const productsAPI = new prodAPI();
24 changes: 15 additions & 9 deletions src/controllers/cart.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,60 @@
import 'regenerator-runtime/runtime';
import { Request, Response } from 'express';
import { cart } from '../models/cart/cartclass';
import { cartAPI } from '../apis/cartapi';

class CartController {
async getProducts(req: Request, res: Response) {
try {
const { id_producto } = req.params;
if (id_producto) {
const singleProduct = await cart.get(id_producto);
const singleProduct = await cartAPI.getProducts(id_producto);
if (singleProduct.length === 0) {
return res
.status(404)
.json({ error: 'No existe un producto con este id' });
}
return res.json({ product: singleProduct });
} else {
const get = await cart.get();
const get = await cartAPI.getProducts();
if (get.length === 0) {
return res.status(404).json({ error: 'No hay un carrito creado' });
}
return res.json({ cart: get });
}
} catch (error) {
console.error(error);
if (error instanceof Error) {
res.status(500).json({ error: error.message });
}
}
}

async addProducts(req: Request, res: Response) {
try {
const { id_producto } = req.params;
if (id_producto) {
const productAdded = await cart.add(id_producto);
const productAdded = await cartAPI.addProduct(id_producto);
return productAdded.length === 0
? res.status(404).json({ error: 'No existe producto con ese id' })
: res.json({ productAdded });
}
} catch (error) {
console.log(error);
if (error instanceof Error) {
res.status(500).json({ error: error.message });
}
}
}

async deleteProducts(req: Request, res: Response) {
try {
const { id_producto } = req.params;
const deletedProduct = await cart.delete(id_producto);
return deletedProduct === -1
const deletedProduct = await cartAPI.deleteProduct(id_producto);
return deletedProduct.length === 0
? res.status(404).json({ error: 'Producto no encontrado o ya eliminado' })
: res.json({ deletedProduct });
} catch (error) {
console.log(error);
if (error instanceof Error) {
res.status(500).json({ error: error.message });
}
}
}
}
Expand Down
30 changes: 30 additions & 0 deletions src/controllers/products.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import 'regenerator-runtime/runtime';
import { Request, Response } from 'express';
import { productsAPI } from '../apis/productsapi';
import { ProductQuery } from '../models/interfaces';

class ProductController {
async getProducts(req: Request, res: Response) {
try {
const { id } = req.params;
const { title, price, code, stock, priceMax, priceMin, stockMax, stockMin } = req.query;

if (id) {
const singleProduct = await productsAPI.getProducts(id);
if (singleProduct.length === 0) {
Expand All @@ -15,6 +18,33 @@ class ProductController {
}
return res.json({ product: singleProduct });
} else {
const query: ProductQuery = {};

if (title) {
let titleLow = title.toString().toLowerCase();
let titleFinal = titleLow.charAt(0).toUpperCase() + titleLow.slice(1)
query.title = titleFinal;
}

if (code) query.code = code.toString();

if (priceMax) query.priceMax = Number(priceMax);

if (priceMin) query.priceMin = Number(priceMin);

if (stockMax) query.stockMax = Number(stockMax);

if (stockMin) query.stockMin = Number(stockMin);

if (Object.keys(query).length) {
const productQuery = await productsAPI.query(query);
if (productQuery.length)
return res.json({
products: productQuery,
});
return res.status(404).json({ error: 'No hay productos que hagan match con la busqueda'})
}

const get = await productsAPI.getProducts();
if (get.length === 0) {
return res.status(404).json({ error: 'No hay productos cargados' });
Expand Down
Binary file added src/firebasekey/TP3.pdf
Binary file not shown.
6 changes: 3 additions & 3 deletions src/knexfile.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Update with your config settings.

export default {
productsmysql: {
servermysql: {
client: 'mysql',
connection: {
host: '192.168.64.2',
Expand All @@ -12,9 +12,9 @@ export default {
migrations: { directory: __dirname + '/db/migrations' },
seeds: { directory: __dirname + '/db/seeds' },
},
productsqlite: {
sqlite: {
client: 'sqlite3',
connection: { filename: './productos' },
connection: { filename: './e-commerce' },
useNullAsDefault: true,
migrations: { directory: __dirname + '/db/migrations' },
seeds: { directory: __dirname + '/db/seeds' },
Expand Down
55 changes: 55 additions & 0 deletions src/models/cart/DAO/firebase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import firebase from 'firebase-admin';
import serviceAccount from '../../../firebasekey/fir-crud-254ad-firebase-adminsdk-mqgvd-eadcca8c0d.json';
import { newProductI, Products, Cart } from '../../interfaces';
import { productsAPI } from '../../../apis/productsapi';

export class CartDAOFirebase {
private db;
private query;

constructor() {
this.db = firebase.firestore();
this.query = this.db.collection('carrito');
}

async get(id?: string): Promise<Products[]> {
if (id) {
const getSpecific = await this.query.doc(id).get();
const specific = getSpecific.data();
const product: Products[] = [];
if (specific) {
product.push({ _id: getSpecific.id, ...specific });
return product;
}
return product;
} else {
const getAll = await this.query.get();
let docs = getAll.docs;
const output = docs.map((doc) => ({
_id: doc.id,
...doc.data(),
}));
return output;
}
}

async add(id: string): Promise<Products[]> {
const getProduct = await productsAPI.getProducts(id);

const doc = this.query.doc(id);
await doc.create(getProduct[0]);
return getProduct;
}

async delete(id: string): Promise<Products[]> {
const getProduct = await this.get(id);
const deletedProduct = [];

if (getProduct.length) {
await this.query.doc(id).delete();
deletedProduct.push(...getProduct);
return deletedProduct;
}
return getProduct;
}
}
94 changes: 94 additions & 0 deletions src/models/cart/DAO/fs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { promises as fs } from 'fs';
import path from 'path';
import { Cart, Products, ProductQuery } from '../../interfaces';

const filePath = path.resolve(__dirname, '../../files/productslog.txt');
const filePathCart = path.resolve(__dirname, '../../files/cartlog.txt');

export class CartDAOFS {
content: Cart[];

constructor() {
this.content = [
{
id: this.randomId(),
timestamp: Date.now(),
products: [],
},
];
}

randomId(): string {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}

async get(id?: string): Promise<Cart[] | Products[]> {
// Reads cart's file
const txtFile: Cart[] = JSON.parse(
await fs.readFile(filePathCart, 'utf-8')
);

// Replace the current array in content with the cart's file
this.content = txtFile.length === 0 ? this.content : txtFile;

// If id exist filter product by id, else return the whole cart's array
const result = id
? this.content[0].products.filter((product) => product._id === id)
: this.content;
return result;
}

async add(id: string): Promise<Products[]> {
// Reads cart's file
const txtFileC: Cart[] = JSON.parse(
await fs.readFile(filePathCart, 'utf-8')
);

// Reads cart's file
this.content = txtFileC.length === 0 ? this.content : txtFileC;

// Reads the products file
const txtFile: Products[] = JSON.parse(
await fs.readFile(filePath, 'utf-8')
);

// Filtering a single product from product file by passed id
const newProduct = txtFile.filter((product) => product._id === id);

// Pushing the filtered product into the cart's products array
this.content[0].products.push(...newProduct);

// Re-write the cart's file
await fs.writeFile(filePathCart, JSON.stringify(this.content, null, 2));

// Return an empty array if the product does not exist, else return the array with the matched product
return newProduct.length === 0 ? [] : newProduct;
}

async delete(id: string): Promise<Products[]> {
// Reads cart's file
this.content = JSON.parse(await fs.readFile(filePathCart, 'utf-8'));

// Mapping a new array by id if exists returns an the id else returns -1
const arrayPosition: number = this.content[0].products
.map((product) => product._id)
.indexOf(id);

// Filtering the deleted product into a new Array
const deletedProduct: Products[] = this.content[0].products.filter(
(product) => product._id == id
);

// If the product exists, remove the product from the cart's products array
arrayPosition !== -1 && this.content[0].products.splice(arrayPosition, 1);

// Re-write the cart's file
await fs.writeFile(filePathCart, JSON.stringify(this.content, null, 2));

// Return the deleted product if the product exist else return []
return arrayPosition === -1 ? [] : deletedProduct;
}

}
Loading

0 comments on commit af885d6

Please sign in to comment.