Skip to content

Commit

Permalink
Splitting the common helper + small refactor (#150)
Browse files Browse the repository at this point in the history
Decent size refactor.
  • Loading branch information
ourwarmhouse committed Jun 13, 2020
1 parent 29feaf8 commit 2c0e99b
Show file tree
Hide file tree
Showing 27 changed files with 830 additions and 731 deletions.
1 change: 1 addition & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
}
}
}],
"prefer-template": 1,
"space-before-function-paren": 0,
"space-before-blocks": ["error", "never"],
"camelcase": 0,
Expand Down
28 changes: 18 additions & 10 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const helmet = require('helmet');
const colors = require('colors');
const cron = require('node-cron');
const crypto = require('crypto');
const common = require('./lib/common');
const { getConfig, getPaymentConfig, updateConfigLocal } = require('./lib/config');
const { runIndexing } = require('./lib/indexing');
const { addSchemas } = require('./lib/schema');
const { initDb, getDbUri } = require('./lib/db');
Expand All @@ -29,7 +29,7 @@ const Ajv = require('ajv');
const ajv = new Ajv({ useDefaults: true });

// get config
const config = common.getConfig();
const config = getConfig();

const baseConfig = ajv.validate(require('./config/settingsSchema'), config);
if(baseConfig === false){
Expand Down Expand Up @@ -248,7 +248,7 @@ handlebars = handlebars.create({
return '<h2 class="text-success">Your payment has been successfully processed</h2>';
}
if(status === 'Pending'){
const paymentConfig = common.getPaymentConfig();
const paymentConfig = getPaymentConfig();
if(config.paymentGateway === 'instore'){
return `<h2 class="text-warning">${paymentConfig.resultMessage}</h2>`;
}
Expand Down Expand Up @@ -290,7 +290,7 @@ handlebars = handlebars.create({
},
snip: (text) => {
if(text && text.length > 155){
return text.substring(0, 155) + '...';
return `${text.substring(0, 155)}...`;
}
return text;
},
Expand Down Expand Up @@ -327,12 +327,12 @@ const store = new MongoStore({
if(!config.secretCookie || config.secretCookie === ''){
const randomString = crypto.randomBytes(20).toString('hex');
config.secretCookie = randomString;
common.updateConfigLocal({ secretCookie: randomString });
updateConfigLocal({ secretCookie: randomString });
}
if(!config.secretSession || config.secretSession === ''){
const randomString = crypto.randomBytes(20).toString('hex');
config.secretSession = randomString;
common.updateConfigLocal({ secretSession: randomString });
updateConfigLocal({ secretSession: randomString });
}

app.enable('trust proxy');
Expand Down Expand Up @@ -407,6 +407,10 @@ app.use((req, res, next) => {
if(app.get('env') === 'development'){
app.use((err, req, res, next) => {
console.error(colors.red(err.stack));
if(err && err.code === 'EACCES'){
res.status(400).json({ message: 'File upload error. Please try again.' });
return;
}
res.status(err.status || 500);
res.render('error', {
message: err.message,
Expand All @@ -420,6 +424,10 @@ if(app.get('env') === 'development'){
// no stacktraces leaked to user
app.use((err, req, res, next) => {
console.error(colors.red(err.stack));
if(err && err.code === 'EACCES'){
res.status(400).json({ message: 'File upload error. Please try again.' });
return;
}
res.status(err.status || 500);
res.render('error', {
message: err.message,
Expand All @@ -443,7 +451,7 @@ app.on('uncaughtException', (err) => {
initDb(config.databaseConnectionString, async (err, db) => {
// On connection error we display then exit
if(err){
console.log(colors.red('Error connecting to MongoDB: ' + err));
console.log(colors.red(`Error connecting to MongoDB: ${err}`));
process.exit(2);
}

Expand Down Expand Up @@ -479,7 +487,7 @@ initDb(config.databaseConnectionString, async (err, db) => {
try{
await runIndexing(app);
}catch(ex){
console.error(colors.red('Error setting up indexes:' + ex.message));
console.error(colors.red(`Error setting up indexes:${ex.message}`));
}
}

Expand All @@ -488,10 +496,10 @@ initDb(config.databaseConnectionString, async (err, db) => {
await app.listen(app.get('port'));
app.emit('appStarted');
if(process.env.NODE_ENV !== 'test'){
console.log(colors.green('expressCart running on host: http://localhost:' + app.get('port')));
console.log(colors.green(`expressCart running on host: http://localhost:${app.get('port')}`));
}
}catch(ex){
console.error(colors.red('Error starting expressCart app:' + ex.message));
console.error(colors.red(`Error starting expressCart app:${ex.message}`));
process.exit(2);
}
});
Expand Down
132 changes: 132 additions & 0 deletions lib/cart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
const {
getConfig
} = require('./config');

const updateTotalCart = async (req, res) => {
const config = getConfig();
const db = req.app.db;

req.session.totalCartAmount = 0;
req.session.totalCartItems = 0;
req.session.totalCartProducts = 0;

// If cart is empty return zero values
if(!req.session.cart){
return;
}

Object.keys(req.session.cart).forEach((item) => {
req.session.totalCartAmount = req.session.totalCartAmount + req.session.cart[item].totalItemPrice;
req.session.totalCartProducts = req.session.totalCartProducts + req.session.cart[item].quantity;
});

// Update the total items in cart for the badge
req.session.totalCartItems = Object.keys(req.session.cart).length;

// Update the total amount not including shipping/discounts
req.session.totalCartNetAmount = req.session.totalCartAmount;

// Calculate shipping using the loaded module
config.modules.loaded.shipping.calculateShipping(
req.session.totalCartNetAmount,
config,
req
);

// If discount module enabled
if(config.modules.loaded.discount){
// Recalculate discounts
const discount = await db.discounts.findOne({ code: req.session.discountCode });
if(discount){
config.modules.loaded.discount.calculateDiscount(
discount,
req
);
}else{
// If discount code is not found, remove it
delete req.session.discountCode;
req.session.totalCartDiscount = 0;
}
}

// Calculate our total amount removing discount and adding shipping
req.session.totalCartAmount = (req.session.totalCartNetAmount - req.session.totalCartDiscount) + req.session.totalCartShipping;
};

const updateSubscriptionCheck = (req, res) => {
// If cart is empty
if(!req.session.cart || req.session.cart.length === 0){
req.session.cartSubscription = null;
return;
}

Object.keys(req.session.cart).forEach((item) => {
if(item.productSubscription){
req.session.cartSubscription = item.productSubscription;
}else{
req.session.cartSubscription = null;
}
});
};

const emptyCart = async (req, res, type, customMessage) => {
const db = req.app.db;

// Remove from session
delete req.session.cart;
delete req.session.shippingAmount;
delete req.session.orderId;
delete req.session.cartSubscription;
delete req.session.discountCode;

// Remove cart from DB
await db.cart.deleteOne({ sessionId: req.session.id });

// update total cart
await updateTotalCart(req, res);

// Update checking cart for subscription
updateSubscriptionCheck(req, res);

// Set returned message
let message = 'Cart successfully emptied';
if(customMessage){
message = customMessage;
}

if(type === 'function'){
return;
}

// If POST, return JSON else redirect nome
if(type === 'json'){
res.status(200).json({ message: message, totalCartItems: 0 });
return;
}

req.session.message = message;
req.session.messageType = 'success';
res.redirect('/');
};

const clearCustomer = (req) => {
// Clear our session
req.session.customerPresent = null;
req.session.customerEmail = null;
req.session.customerFirstname = null;
req.session.customerLastname = null;
req.session.customerAddress1 = null;
req.session.customerAddress2 = null;
req.session.customerCountry = null;
req.session.customerState = null;
req.session.customerPostcode = null;
req.session.customerPhone = null;
req.session.orderComment = null;
};

module.exports = {
updateTotalCart,
updateSubscriptionCheck,
emptyCart,
clearCustomer
};
Loading

0 comments on commit 2c0e99b

Please sign in to comment.