react_convert
Mark Moffat 2018-01-06 20:35:49 +01:00
parent 7c1c94da72
commit defad4e76f
4 changed files with 81 additions and 97 deletions

24
app.js
View File

@ -12,9 +12,8 @@ const MongoClient = require('mongodb').MongoClient;
const numeral = require('numeral'); const numeral = require('numeral');
const helmet = require('helmet'); const helmet = require('helmet');
const colors = require('colors'); const colors = require('colors');
const config = require('./config/settings.json');
const common = require('./routes/common'); const common = require('./routes/common');
const frameguard = require('frameguard');
let handlebars = require('express-handlebars'); let handlebars = require('express-handlebars');
// require the routes // require the routes
@ -156,9 +155,6 @@ handlebars = handlebars.create({
} }
}); });
// get config
let config = common.getConfig();
// var session store // var session store
let store = new MongoStore({ let store = new MongoStore({
uri: config.databaseConnectionString, uri: config.databaseConnectionString,
@ -184,12 +180,6 @@ app.use(session({
store: store store: store
})); }));
// allows for codecanyon
app.use(frameguard({
action: 'allow-from',
domain: 'http://preview.codecanyon.net'
}));
// serving static content // serving static content
app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public')));
@ -258,6 +248,7 @@ MongoClient.connect(config.databaseConnectionString, {}, (err, client) => {
// setup the collections // setup the collections
db.users = db.collection('users'); db.users = db.collection('users');
db.config = db.collection('config');
db.products = db.collection('products'); db.products = db.collection('products');
db.orders = db.collection('orders'); db.orders = db.collection('orders');
db.pages = db.collection('pages'); db.pages = db.collection('pages');
@ -271,9 +262,14 @@ MongoClient.connect(config.databaseConnectionString, {}, (err, client) => {
console.error(colors.red('Error setting up indexes:' + err)); console.error(colors.red('Error setting up indexes:' + err));
process.exit(); process.exit();
} }
// lift the app
app.listen(app.get('port'), () => { // Loads the config file into the DB
console.log(colors.green('expressCart running on host: http://localhost:' + app.get('port'))); db.config.update({}, config, {upsert: true})
.then(() => {
// lift the app
app.listen(app.get('port'), () => {
console.log(colors.green('expressCart running on host: http://localhost:' + app.get('port')));
});
}); });
}); });
}); });

View File

@ -5,7 +5,7 @@
"private": true, "private": true,
"scripts": { "scripts": {
"start": "node app.js", "start": "node app.js",
"dist": "npm run minify && gulp dist" "deploy": "gulp deploy"
}, },
"dependencies": { "dependencies": {
"async": "^2.6.0", "async": "^2.6.0",

View File

@ -31,7 +31,7 @@ exports.showCartCloseBtn = function(page){
exports.addSitemapProducts = function(req, res, cb){ exports.addSitemapProducts = function(req, res, cb){
let db = req.app.db; let db = req.app.db;
let async = require('async'); let async = require('async');
let config = this.getConfig(); let config = exports.getConfig();
let hostname = config.baseUrl; let hostname = config.baseUrl;
exports.dbQuery(db.products, {productPublished: 'true'}, null, null, (err, products) => { exports.dbQuery(db.products, {productPublished: 'true'}, null, null, (err, products) => {
@ -70,7 +70,7 @@ exports.clearSessionValue = function(session, sessionVar){
}; };
exports.updateTotalCartAmount = function(req, res){ exports.updateTotalCartAmount = function(req, res){
let config = this.getConfig(); let config = exports.getConfig();
req.session.totalCartAmount = 0; req.session.totalCartAmount = 0;
@ -157,11 +157,6 @@ exports.getConfig = function(){
config.env = ''; config.env = '';
} }
// default DB to embedded
if(typeof config.databaseType === 'undefined'){
config.databaseType = 'embedded';
}
// setup theme // setup theme
config.themeViews = ''; config.themeViews = '';
if(typeof config.theme !== 'undefined' && config.theme !== ''){ if(typeof config.theme !== 'undefined' && config.theme !== ''){
@ -169,11 +164,7 @@ exports.getConfig = function(){
} }
// if db set to mongodb override connection with MONGODB_CONNECTION_STRING env var // if db set to mongodb override connection with MONGODB_CONNECTION_STRING env var
if(config.databaseType === 'mongodb'){ config.databaseConnectionString = process.env.MONGODB_CONNECTION_STRING || config.databaseConnectionString;
config.databaseConnectionString = process.env.MONGODB_CONNECTION_STRING || config.databaseConnectionString;
}
console.log('got config');
return config; return config;
}; };
@ -406,7 +397,6 @@ exports.getId = function(id){
// run the DB query // run the DB query
exports.dbQuery = function(db, query, sort, limit, callback){ exports.dbQuery = function(db, query, sort, limit, callback){
let config = exports.getConfig();
if(sort && limit){ if(sort && limit){
db.find(query).sort(sort).limit(parseInt(limit)).toArray((err, results) => { db.find(query).sort(sort).limit(parseInt(limit)).toArray((err, results) => {
if(err){ if(err){

View File

@ -5,8 +5,8 @@ const _ = require('lodash');
const common = require('./common'); const common = require('./common');
router.get('/payment/:orderId', (req, res, next) => { router.get('/payment/:orderId', (req, res, next) => {
var db = req.app.db; let db = req.app.db;
var config = common.getConfig(); let config = common.getConfig();
// render the payment complete message // render the payment complete message
db.orders.findOne({_id: common.getId(req.params.orderId)}, (err, result) => { db.orders.findOne({_id: common.getId(req.params.orderId)}, (err, result) => {
@ -29,7 +29,7 @@ router.get('/payment/:orderId', (req, res, next) => {
}); });
router.get('/checkout', (req, res, next) => { router.get('/checkout', (req, res, next) => {
var config = common.getConfig(); let config = common.getConfig();
// if there is no items in the cart then render a failure // if there is no items in the cart then render a failure
if(!req.session.cart){ if(!req.session.cart){
@ -56,7 +56,7 @@ router.get('/checkout', (req, res, next) => {
}); });
router.get('/pay', (req, res, next) => { router.get('/pay', (req, res, next) => {
var config = common.getConfig(); let config = common.getConfig();
// if there is no items in the cart then render a failure // if there is no items in the cart then render a failure
if(!req.session.cart){ if(!req.session.cart){
@ -96,10 +96,10 @@ router.get('/cartPartial', (req, res) => {
// show an individual product // show an individual product
router.get('/product/:id', (req, res) => { router.get('/product/:id', (req, res) => {
var db = req.app.db; let db = req.app.db;
var config = common.getConfig(); let config = common.getConfig();
db.products.findOne({$or: [{_id: common.getId(req.params.id)}, {productPermalink: req.params.id}]}, function (err, result){ db.products.findOne({$or: [{_id: common.getId(req.params.id)}, {productPermalink: req.params.id}]}, (err, result) => {
// render 404 if page is not published // render 404 if page is not published
if(err){ if(err){
res.render('error', {message: '404 - Page not found', helpers: req.handlebars.helpers}); res.render('error', {message: '404 - Page not found', helpers: req.handlebars.helpers});
@ -107,13 +107,13 @@ router.get('/product/:id', (req, res) => {
if(err || result == null || result.productPublished === 'false'){ if(err || result == null || result.productPublished === 'false'){
res.render('error', {message: '404 - Page not found', helpers: req.handlebars.helper}); res.render('error', {message: '404 - Page not found', helpers: req.handlebars.helper});
}else{ }else{
var productOptions = {}; let productOptions = {};
if(result.productOptions){ if(result.productOptions){
productOptions = JSON.parse(result.productOptions); productOptions = JSON.parse(result.productOptions);
} }
// show the view // show the view
common.getImages(result._id, req, res, function (images){ common.getImages(result._id, req, res, (images) => {
res.render(config.themeViews + 'product', { res.render(config.themeViews + 'product', {
title: result.productTitle, title: result.productTitle,
result: result, result: result,
@ -137,7 +137,7 @@ router.get('/product/:id', (req, res) => {
}); });
// logout // logout
router.get('/logout', function (req, res){ router.get('/logout', (req, res) => {
req.session.user = null; req.session.user = null;
req.session.message = null; req.session.message = null;
req.session.messageType = null; req.session.messageType = null;
@ -145,10 +145,10 @@ router.get('/logout', function (req, res){
}); });
// login form // login form
router.get('/login', function (req, res){ router.get('/login', (req, res) => {
var db = req.app.db; let db = req.app.db;
db.users.count({}, function(err, userCount){ db.users.count({}, (err, userCount) => {
if(err){ if(err){
// if there are no users set the "needsSetup" session // if there are no users set the "needsSetup" session
req.session.needsSetup = true; req.session.needsSetup = true;
@ -176,10 +176,10 @@ router.get('/login', function (req, res){
}); });
// setup form is shown when there are no users setup in the DB // setup form is shown when there are no users setup in the DB
router.get('/setup', function (req, res){ router.get('/setup', (req, res) => {
var db = req.app.db; let db = req.app.db;
db.users.count({}, function (err, userCount){ db.users.count({}, (err, userCount) => {
if(err){ if(err){
console.error(colors.red('Error getting users for setup', err)); console.error(colors.red('Error getting users for setup', err));
} }
@ -198,17 +198,16 @@ router.get('/setup', function (req, res){
}); });
}else{ }else{
res.redirect('/login'); res.redirect('/login');
return;
} }
}); });
}); });
// login the user and check the password // login the user and check the password
router.post('/login_action', function (req, res){ router.post('/login_action', (req, res) => {
var db = req.app.db; let db = req.app.db;
var bcrypt = req.bcrypt; let bcrypt = req.bcrypt;
db.users.findOne({userEmail: req.body.email}, function (err, user){ db.users.findOne({userEmail: req.body.email}, (err, user) => {
if(err){ if(err){
req.session.message = 'Cannot find user.'; req.session.message = 'Cannot find user.';
req.session.messageType = 'danger'; req.session.messageType = 'danger';
@ -234,21 +233,20 @@ router.post('/login_action', function (req, res){
req.session.message = 'Access denied. Check password and try again.'; req.session.message = 'Access denied. Check password and try again.';
req.session.messageType = 'danger'; req.session.messageType = 'danger';
res.redirect('/login'); res.redirect('/login');
return;
} }
} }
}); });
}); });
// search products // search products
router.get('/search/:searchTerm/:pageNum?', function (req, res){ router.get('/search/:searchTerm/:pageNum?', (req, res) => {
var searchTerm = req.params.searchTerm; let searchTerm = req.params.searchTerm;
var productsIndex = req.app.productsIndex; let productsIndex = req.app.productsIndex;
var config = common.getConfig(); let config = common.getConfig();
var numberProducts = config.productsPerPage ? config.productsPerPage : 6; let numberProducts = config.productsPerPage ? config.productsPerPage : 6;
var lunrIdArray = []; let lunrIdArray = [];
productsIndex.search(searchTerm).forEach(function(id){ productsIndex.search(searchTerm).forEach((id) => {
if(config.databaseType !== 'embedded'){ if(config.databaseType !== 'embedded'){
lunrIdArray.push(common.getId(id.ref)); lunrIdArray.push(common.getId(id.ref));
}else{ }else{
@ -256,13 +254,13 @@ router.get('/search/:searchTerm/:pageNum?', function (req, res){
} }
}); });
var pageNum = 1; let pageNum = 1;
if(req.params.pageNum){ if(req.params.pageNum){
pageNum = req.params.pageNum; pageNum = req.params.pageNum;
} }
// we search on the lunr indexes // we search on the lunr indexes
getData(req, pageNum, {_id: {$in: lunrIdArray}}, function (err, results){ getData(req, pageNum, {_id: {$in: lunrIdArray}}, (err, results) => {
if(err){ if(err){
console.error(colors.red('Error searching for products', err)); console.error(colors.red('Error searching for products', err));
} }
@ -290,14 +288,14 @@ router.get('/search/:searchTerm/:pageNum?', function (req, res){
}); });
// search products // search products
router.get('/category/:cat/:pageNum?', function (req, res){ router.get('/category/:cat/:pageNum?', (req, res) => {
var searchTerm = req.params.cat; let searchTerm = req.params.cat;
var productsIndex = req.app.productsIndex; let productsIndex = req.app.productsIndex;
var config = common.getConfig(); let config = common.getConfig();
var numberProducts = config.productsPerPage ? config.productsPerPage : 6; let numberProducts = config.productsPerPage ? config.productsPerPage : 6;
var lunrIdArray = []; let lunrIdArray = [];
productsIndex.search(searchTerm).forEach(function(id){ productsIndex.search(searchTerm).forEach((id) => {
if(config.databaseType !== 'embedded'){ if(config.databaseType !== 'embedded'){
lunrIdArray.push(common.getId(id.ref)); lunrIdArray.push(common.getId(id.ref));
}else{ }else{
@ -305,15 +303,15 @@ router.get('/category/:cat/:pageNum?', function (req, res){
} }
}); });
var menuLink = _.find(common.getMenu().items, function(obj){ return obj.link === searchTerm; }); let menuLink = _.find(common.getMenu().items, (obj) => { return obj.link === searchTerm; });
var pageNum = 1; let pageNum = 1;
if(req.params.pageNum){ if(req.params.pageNum){
pageNum = req.params.pageNum; pageNum = req.params.pageNum;
} }
// we search on the lunr indexes // we search on the lunr indexes
getData(req, pageNum, {_id: {$in: lunrIdArray}}, function (err, results){ getData(req, pageNum, {_id: {$in: lunrIdArray}}, (err, results) => {
if(err){ if(err){
console.error(colors.red('Error getting products for category', err)); console.error(colors.red('Error getting products for category', err));
} }
@ -342,15 +340,15 @@ router.get('/category/:cat/:pageNum?', function (req, res){
}); });
// return sitemap // return sitemap
router.get('/sitemap.xml', function (req, res, next){ router.get('/sitemap.xml', (req, res, next) => {
var sm = require('sitemap'); let sm = require('sitemap');
var config = common.getConfig(); let config = common.getConfig();
common.addSitemapProducts(req, res, function (err, products){ common.addSitemapProducts(req, res, (err, products) => {
if(err){ if(err){
console.error(colors.red('Error generating sitemap.xml', err)); console.error(colors.red('Error generating sitemap.xml', err));
} }
var sitemap = sm.createSitemap( let sitemap = sm.createSitemap(
{ {
hostname: config.baseUrl, hostname: config.baseUrl,
cacheTime: 600000, cacheTime: 600000,
@ -359,11 +357,11 @@ router.get('/sitemap.xml', function (req, res, next){
] ]
}); });
var currentUrls = sitemap.urls; let currentUrls = sitemap.urls;
var mergedUrls = currentUrls.concat(products); let mergedUrls = currentUrls.concat(products);
sitemap.urls = mergedUrls; sitemap.urls = mergedUrls;
// render the sitemap // render the sitemap
sitemap.toXML(function(err, xml){ sitemap.toXML((err, xml) => {
if(err){ if(err){
return res.status(500).end(); return res.status(500).end();
} }
@ -374,11 +372,11 @@ router.get('/sitemap.xml', function (req, res, next){
}); });
}); });
router.get('/page/:pageNum', function (req, res, next){ router.get('/page/:pageNum', (req, res, next) => {
var config = common.getConfig(); let config = common.getConfig();
var numberProducts = config.productsPerPage ? config.productsPerPage : 6; let numberProducts = config.productsPerPage ? config.productsPerPage : 6;
getData(req, req.params.pageNum, {}, function (err, results){ getData(req, req.params.pageNum, {}, (err, results) => {
if(err){ if(err){
console.error(colors.red('Error getting products for page', err)); console.error(colors.red('Error getting products for page', err));
} }
@ -403,14 +401,14 @@ router.get('/page/:pageNum', function (req, res, next){
}); });
}); });
router.get('/:page?', function (req, res, next){ router.get('/:page?', (req, res, next) => {
var db = req.app.db; let db = req.app.db;
var config = common.getConfig(); let config = common.getConfig();
var numberProducts = config.productsPerPage ? config.productsPerPage : 6; let numberProducts = config.productsPerPage ? config.productsPerPage : 6;
// if no page is specified, just render page 1 of the cart // if no page is specified, just render page 1 of the cart
if(!req.params.page){ if(!req.params.page){
getData(req, 1, {}, function (err, results){ getData(req, 1, {}, (err, results) => {
if(err){ if(err){
console.error(colors.red('Error getting products for page', err)); console.error(colors.red('Error getting products for page', err));
} }
@ -439,7 +437,7 @@ router.get('/:page?', function (req, res, next){
return; return;
} }
// lets look for a page // lets look for a page
db.pages.findOne({pageSlug: req.params.page, pageEnabled: 'true'}, function (err, page){ db.pages.findOne({pageSlug: req.params.page, pageEnabled: 'true'}, (err, page) => {
if(err){ if(err){
console.error(colors.red('Error getting page', err)); console.error(colors.red('Error getting page', err));
} }
@ -473,35 +471,35 @@ router.get('/:page?', function (req, res, next){
} }
}); });
var getData = function (req, page, query, cb){ const getData = function (req, page, query, cb){
var db = req.app.db; let db = req.app.db;
var config = common.getConfig(); let config = common.getConfig();
var numberProducts = config.productsPerPage ? config.productsPerPage : 6; let numberProducts = config.productsPerPage ? config.productsPerPage : 6;
var skip = 0; let skip = 0;
if(page > 1){ if(page > 1){
skip = (page - 1) * numberProducts; skip = (page - 1) * numberProducts;
} }
query['productPublished'] = 'true'; query['productPublished'] = 'true';
db.products.count(query, function (err, totalProducts){ db.products.count(query, (err, totalProducts) => {
if(err){ if(err){
console.error(colors.red('Error getting total product count', err)); console.error(colors.red('Error getting total product count', err));
} }
if(config.databaseType === 'embedded'){ if(config.databaseType === 'embedded'){
db.products.find(query).skip(skip).limit(parseInt(numberProducts)).exec(function (err, results){ db.products.find(query).skip(skip).limit(parseInt(numberProducts)).exec((err, results) => {
if(err){ if(err){
cb('Error retrieving products', null); cb(new Error('Error retrieving products'), null);
}else{ }else{
cb(null, {data: results, totalProducts: totalProducts}); cb(null, {data: results, totalProducts: totalProducts});
} }
}); });
}else{ }else{
db.products.find(query).skip(skip).limit(parseInt(numberProducts)).toArray(function (err, results){ db.products.find(query).skip(skip).limit(parseInt(numberProducts)).toArray((err, results) => {
if(err){ if(err){
cb('Error retrieving products', null); cb(new Error('Error retrieving products'), null);
}else{ }else{
cb(null, {data: results, totalProducts: totalProducts}); cb(null, {data: results, totalProducts: totalProducts});
} }