continuing to connect models and services

This commit is contained in:
Mikayla Dobson
2022-09-26 15:49:36 -05:00
parent cff08d91d6
commit f4a7ced887
11 changed files with 108 additions and 33 deletions

View File

@@ -2,8 +2,10 @@ const { Client } = require('pg');
require('dotenv').config({ path: "../.env" }); require('dotenv').config({ path: "../.env" });
async function main() { async function main() {
console.log("Beginning database setup.");
const client = new Client({ connectionString: process.env.CONNECTION }); const client = new Client({ connectionString: process.env.CONNECTION });
await client.connect().then(console.log("Connection successful.")); await client.connect().then(console.log("Now connected to postgres"));
// user // user
const createUserTable = ` const createUserTable = `
@@ -11,8 +13,8 @@ async function main() {
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY NOT NULL, id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY NOT NULL,
email VARCHAR NOT NULL, email VARCHAR NOT NULL,
password VARCHAR NOT NULL, password VARCHAR NOT NULL,
firstname VARCHAR NOT NULL, firstname VARCHAR,
lastname VARCHAR NOT NULL lastname VARCHAR
); );
`; `;
@@ -29,7 +31,7 @@ async function main() {
CREATE TABLE IF NOT EXISTS orders ( CREATE TABLE IF NOT EXISTS orders (
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY NOT NULL, id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY NOT NULL,
userId INT REFERENCES users(id), userId INT REFERENCES users(id),
total NUMERIC NOT NULL, total NUMERIC,
delivered BOOLEAN, delivered BOOLEAN,
processed BOOLEAN, processed BOOLEAN,
shipped BOOLEAN shipped BOOLEAN
@@ -61,7 +63,8 @@ async function main() {
description VARCHAR, description VARCHAR,
categoryId INT REFERENCES category(id), categoryId INT REFERENCES category(id),
regionId INT REFERENCES region(id), regionId INT REFERENCES region(id),
price NUMERIC price NUMERIC,
inventory INT
); );
`; `;
@@ -69,7 +72,8 @@ async function main() {
const createProductsCarts = ` const createProductsCarts = `
CREATE TABLE IF NOT EXISTS products_carts ( CREATE TABLE IF NOT EXISTS products_carts (
productId INT REFERENCES product(id), productId INT REFERENCES product(id),
cartId INT REFERENCES cart(id) cartId INT REFERENCES cart(id),
quantity INT
); );
`; `;
@@ -94,11 +98,11 @@ async function main() {
} }
await client.end(); await client.end();
status = "Database setup successful!"; status = "Database initialization successful.";
} catch(e) { } catch(e) {
status = e; status = e;
} finally { } finally {
if (status !== "Database setup successful!") { if (status !== "Database initialization successful.") {
throw new Error(status); throw new Error(status);
} }
} }

View File

@@ -1,5 +0,0 @@
async function main() {
return;
}

View File

@@ -1,5 +1,4 @@
import csv import csv
from re import M
from psycopg2 import sql from psycopg2 import sql
# function to read from a given csv file into postgres # function to read from a given csv file into postgres

View File

@@ -1,6 +1,5 @@
from insert_file_contents import insert_file_contents from insert_file_contents import insert_file_contents
import psycopg2 import psycopg2
from psycopg2 import sql
import os import os
# read data from environment if present # read data from environment if present
@@ -26,9 +25,12 @@ os.close(fd)
conn = psycopg2.connect("dbname=e-commerce-092122 user=mikayladobson") conn = psycopg2.connect("dbname=e-commerce-092122 user=mikayladobson")
cur = conn.cursor() cur = conn.cursor()
print("Now attempting to populate database...")
# read contents of each file into postgres # read contents of each file into postgres
insert_file_contents(conn, cur, "./data/categories.csv", 'category') insert_file_contents(conn, cur, "./data/categories.csv", 'category')
insert_file_contents(conn, cur, "./data/regions.csv", 'region') insert_file_contents(conn, cur, "./data/regions.csv", 'region')
insert_file_contents(conn, cur, "./data/products.csv", 'product') insert_file_contents(conn, cur, "./data/products.csv", 'product')
print("Database insertions executed successfully.") print("Insertions executed successfully.")
print("Database preparations complete!")

View File

@@ -3,18 +3,51 @@ const pgp = require('pg-promise')({ capSQL: true });
module.exports = class CartProductModel { module.exports = class CartProductModel {
async create(data) { async create(data) {
try {
const statement = pgp.helpers.insert(data, null, 'products_orders') + 'RETURNING *';
const result = await db.query(statement);
if (result.rows.length) return result.rows[0];
return null;
} catch(e) {
throw new Error(e);
}
} }
async find(cartid) { async find(cartid) {
try {
const statement = "SELECT * FROM products_orders WHERE cartid = $1";
const values = [cartid];
const result = await db.query(statement, values);
if (result.rows.length) return result.rows[0];
return [];
} catch(e) {
throw new Error(e);
}
} }
async update(data) { async update(data) {
const { id } = data;
try {
const condition = pgp.as.format("WHERE id = $1", [id]);
const statement = pgp.helpers.update(data, null, 'products_orders') + condition;
const result = await db.query(statement);
if (result.rows.length) return result.rows[0];
return null;
} catch(e) {
throw new Error(e);
}
} }
async delete(productid) { async delete(productid) {
try {
const statement = "DELETE FROM products_orders WHERE id = $1 RETURNING *";
const values = [productid];
const result = await db.query(statement, values);
if (result.rows.length) return result.rows[0];
return null;
} catch(e) {
throw new Error(e);
}
} }
} }

View File

@@ -1,17 +1,44 @@
module.exports = class OrderModel { const db = require('../db/Pool');
async create() { const pgp = require('pg-promise')({ capSQL: true });
/**
* TODO: conceptualize and implement order lifecycle, from not submitted,
* to submitted/not shipped, to shipped and pending, to delivered?
**/
module.exports = class OrderModel {
async create(userid) {
try {
const statement = pgp.helpers.insert(userid, null, 'orders') + 'RETURNING *';
const result = await db.query(statement);
if (result.rows.length) return result.rows[0];
return null;
} catch(e) {
throw new Error(e);
}
} }
async update(data) { async update(data) {
try {
} catch(e) {
throw new Error(e);
}
} }
async findByUser(userid) { async findByUser(userid) {
try {
} catch(e) {
throw new Error(e);
}
} }
async findByOrderId(orderid) { async findByOrderId(orderid) {
try {
} catch(e) {
throw new Error(e);
}
} }
} }

View File

@@ -6,8 +6,7 @@
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js", "start": "nodemon server.js",
"seed": "cd db && node seed.js", "seed": "cd db && node seed.js && cd util && python3 main.py"
"populate": "cd db/util && python3 main.py"
}, },
"engines": { "engines": {
"node": "v16.13.1" "node": "v16.13.1"

View File

@@ -1,11 +1,10 @@
require('dotenv').config(); require('dotenv').config();
const express = require('express'); const express = require('express');
const loaders = require('./loaders');
const PORT = process.env.PORT || 8088; const PORT = process.env.PORT || 8088;
const app = express();
const loaders = require('./loaders');
async function start() { async function start() {
const app = express();
loaders(app); loaders(app);
app.listen(PORT, () => { app.listen(PORT, () => {

View File

@@ -36,10 +36,5 @@ module.exports = class AuthService {
} }
} }
// yet to be implemented
async deleteOne(data) {
return data;
}
// TO IMPLEMENT: google, facebook passport strategies // TO IMPLEMENT: google, facebook passport strategies
} }

View File

@@ -1,6 +1,11 @@
const createError = require('http-errors'); const createError = require('http-errors');
const CartModel = require('../models/CartModel'); const CartModel = require('../models/CartModel');
const OrderModel = require('../models/OrderModel');
const CartProductModel = require('../models/CartProductModel');
const CartInstance = new CartModel(); const CartInstance = new CartModel();
const OrderInstance = new OrderModel();
const CartProductInstance = new CartProductModel();
module.exports = class CartService { module.exports = class CartService {
async create(userid) { async create(userid) {
@@ -14,6 +19,14 @@ module.exports = class CartService {
async addItem(userid, item) { async addItem(userid, item) {
const cart = await CartInstance.findOneByUserId(userid); const cart = await CartInstance.findOneByUserId(userid);
const item = "await CartProductInstance.create(item)"; const item = await CartProductInstance.create(item);
}
async removeItem(userid, item) {
}
async checkout() {
} }
} }

View File

@@ -0,0 +1,9 @@
const OrderModel = require('../models/OrderModel');
const OrderInstance = new OrderModel();
module.exports = class OrderService {
async create(userid) {
const result = await OrderInstance.create(userid);
if (!result) throw new Error();
}
}