Skip to content

Commit

Permalink
Ported app to use the official mongodb driver, created User, Product,…
Browse files Browse the repository at this point in the history
… Cart, Order models and related operations like add to cart, create new order etc
  • Loading branch information
rituparna-ui committed Jul 24, 2022
1 parent 49ae122 commit 439600c
Show file tree
Hide file tree
Showing 17 changed files with 378 additions and 102 deletions.
24 changes: 14 additions & 10 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ const express = require('express');
const bodyParser = require('body-parser');

const errorController = require('./controllers/error');
const sequelize = require('./util/database');
const mongoConnect = require('./util/database').mongoConnect;
const User = require('./models/user');

const app = express();

Expand All @@ -17,17 +18,20 @@ const shopRoutes = require('./routes/shop');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use((req, res, next) => {
User.findById('5baa2528563f16379fc8a610')
.then(user => {
req.user = new User(user.name, user.email, user.cart, user._id);
next();
})
.catch(err => console.log(err));
});

app.use('/admin', adminRoutes);
app.use(shopRoutes);

app.use(errorController.get404);

sequelize
.sync()
.then(result => {
// console.log(result);
app.listen(3000);
})
.catch(err => {
console.log(err);
});
mongoConnect(() => {
app.listen(3000);
});
46 changes: 29 additions & 17 deletions controllers/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,20 @@ exports.postAddProduct = (req, res, next) => {
const imageUrl = req.body.imageUrl;
const price = req.body.price;
const description = req.body.description;
Product.create({
title: title,
price: price,
imageUrl: imageUrl,
description: description
})
const product = new Product(
title,
price,
description,
imageUrl,
null,
req.user._id
);
product
.save()
.then(result => {
// console.log(result);
console.log('Created Product');
res.redirect('/admin/products');
})
.catch(err => {
console.log(err);
Expand All @@ -35,6 +40,7 @@ exports.getEditProduct = (req, res, next) => {
}
const prodId = req.params.productId;
Product.findById(prodId)
// Product.findById(prodId)
.then(product => {
if (!product) {
return res.redirect('/');
Expand All @@ -55,14 +61,16 @@ exports.postEditProduct = (req, res, next) => {
const updatedPrice = req.body.price;
const updatedImageUrl = req.body.imageUrl;
const updatedDesc = req.body.description;
Product.findById(prodId)
.then(product => {
product.title = updatedTitle;
product.price = updatedPrice;
product.description = updatedDesc;
product.imageUrl = updatedImageUrl;
return product.save();
})

const product = new Product(
updatedTitle,
updatedPrice,
updatedDesc,
updatedImageUrl,
prodId
);
product
.save()
.then(result => {
console.log('UPDATED PRODUCT!');
res.redirect('/admin/products');
Expand All @@ -71,7 +79,7 @@ exports.postEditProduct = (req, res, next) => {
};

exports.getProducts = (req, res, next) => {
Product.findAll()
Product.fetchAll()
.then(products => {
res.render('admin/products', {
prods: products,
Expand All @@ -84,6 +92,10 @@ exports.getProducts = (req, res, next) => {

exports.postDeleteProduct = (req, res, next) => {
const prodId = req.body.productId;
Product.deleteById(prodId);
res.redirect('/admin/products');
Product.deleteById(prodId)
.then(() => {
console.log('DESTROYED PRODUCT');
res.redirect('/admin/products');
})
.catch(err => console.log(err));
};
76 changes: 41 additions & 35 deletions controllers/shop.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
const Product = require('../models/product');
const Cart = require('../models/cart');

exports.getProducts = (req, res, next) => {
Product.findAll()
Product.fetchAll()
.then(products => {
res.render('shop/product-list', {
prods: products,
Expand Down Expand Up @@ -38,7 +37,7 @@ exports.getProduct = (req, res, next) => {
};

exports.getIndex = (req, res, next) => {
Product.findAll()
Product.fetchAll()
.then(products => {
res.render('shop/index', {
prods: products,
Expand All @@ -52,52 +51,59 @@ exports.getIndex = (req, res, next) => {
};

exports.getCart = (req, res, next) => {
Cart.getCart(cart => {
Product.fetchAll(products => {
const cartProducts = [];
for (product of products) {
const cartProductData = cart.products.find(
prod => prod.id === product.id
);
if (cartProductData) {
cartProducts.push({ productData: product, qty: cartProductData.qty });
}
}
req.user
.getCart()
.then(products => {
res.render('shop/cart', {
path: '/cart',
pageTitle: 'Your Cart',
products: cartProducts
products: products
});
});
});
})
.catch(err => console.log(err));
};

exports.postCart = (req, res, next) => {
const prodId = req.body.productId;
Product.findById(prodId, product => {
Cart.addProduct(prodId, product.price);
});
res.redirect('/cart');
Product.findById(prodId)
.then(product => {
return req.user.addToCart(product);
})
.then(result => {
console.log(result);
res.redirect('/cart');
});
};

exports.postCartDeleteProduct = (req, res, next) => {
const prodId = req.body.productId;
Product.findById(prodId, product => {
Cart.deleteProduct(prodId, product.price);
res.redirect('/cart');
});
req.user
.deleteItemFromCart(prodId)
.then(result => {
res.redirect('/cart');
})
.catch(err => console.log(err));
};

exports.getOrders = (req, res, next) => {
res.render('shop/orders', {
path: '/orders',
pageTitle: 'Your Orders'
});
exports.postOrder = (req, res, next) => {
let fetchedCart;
req.user
.addOrder()
.then(result => {
res.redirect('/orders');
})
.catch(err => console.log(err));
};

exports.getCheckout = (req, res, next) => {
res.render('shop/checkout', {
path: '/checkout',
pageTitle: 'Checkout'
});
exports.getOrders = (req, res, next) => {
req.user
.getOrders()
.then(orders => {
res.render('shop/orders', {
path: '/orders',
pageTitle: 'Your Orders',
orders: orders
});
})
.catch(err => console.log(err));
};
95 changes: 73 additions & 22 deletions models/product.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,78 @@
const Sequelize = require('sequelize');
const mongodb = require('mongodb');
const getDb = require('../util/database').getDb;

const sequelize = require('../util/database');
class Product {
constructor(title, price, description, imageUrl, id, userId) {
this.title = title;
this.price = price;
this.description = description;
this.imageUrl = imageUrl;
this._id = id ? new mongodb.ObjectId(id) : null;
this.userId = userId;
}

save() {
const db = getDb();
let dbOp;
if (this._id) {
// Update the product
dbOp = db
.collection('products')
.updateOne({ _id: this._id }, { $set: this });
} else {
dbOp = db.collection('products').insertOne(this);
}
return dbOp
.then(result => {
console.log(result);
})
.catch(err => {
console.log(err);
});
}

static fetchAll() {
const db = getDb();
return db
.collection('products')
.find()
.toArray()
.then(products => {
console.log(products);
return products;
})
.catch(err => {
console.log(err);
});
}

static findById(prodId) {
const db = getDb();
return db
.collection('products')
.find({ _id: new mongodb.ObjectId(prodId) })
.next()
.then(product => {
console.log(product);
return product;
})
.catch(err => {
console.log(err);
});
}

const Product = sequelize.define('product', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
title: Sequelize.STRING,
price: {
type: Sequelize.DOUBLE,
allowNull: false
},
imageUrl: {
type: Sequelize.STRING,
allowNull: false
},
description: {
type: Sequelize.STRING,
allowNull: false
static deleteById(prodId) {
const db = getDb();
return db
.collection('products')
.deleteOne({ _id: new mongodb.ObjectId(prodId) })
.then(result => {
console.log('Deleted');
})
.catch(err => {
console.log(err);
});
}
});
}

module.exports = Product;
Loading

0 comments on commit 439600c

Please sign in to comment.