server optimization

This commit is contained in:
Sergey Yarkov 2019-11-18 19:23:25 +03:00
parent 8c20918fda
commit bfb1d32df0
9 changed files with 136 additions and 171 deletions

4
config/database.js Normal file
View File

@ -0,0 +1,4 @@
module.exports = {
url: 'mongodb://localhost:27017/',
name: 'digital_store'
}

View File

@ -1,15 +1,9 @@
const MongoClient = require('mongodb').MongoClient; const db = require('../database');
const dbName = 'digital_store'; const dbName = db.name;
const routes = {
// Index
indexRoute: function (req, res) {
MongoClient.connect(`mongodb://localhost:27017/${dbName}`, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, db) => {
if (err) throw err;
function indexRoute(req, res, db) {
const dbo = db.db(dbName); const dbo = db.db(dbName);
dbo.collection('storeInfo').find().toArray((err, result) => { dbo.collection('storeInfo').find().toArray((err, result) => {
if (err) throw err; if (err) throw err;
const array = Object.keys(result[0].items) const array = Object.keys(result[0].items)
@ -20,70 +14,28 @@ const routes = {
pageName: 'index', pageName: 'index',
categories categories
}); });
db.close();
}) })
}); }
},
// How-to-buy function getItemsRoute(req, res, db) {
howToBuyRoute: function (req, res) { const dbo = db.db(dbName);
res.render('how-to-buy', {
pageName: 'how-to-buy'
});
},
// Contacts
contactsRoute: function (req, res) {
res.render('contacts', {
pageName: 'contacts'
});
},
// Comments
commentsRoute: function (req, res) {
res.render('comments', {
pageName: 'comments'
});
},
// My-orders
myOrdersRoute: function (req, res) {
res.render('my-orders', {
pageName: 'my-orders'
});
},
// GetItems
getItemsRoute: function (req, res) {
const queryOptions = { const queryOptions = {
auth: 'yYNfW8ynVO18L1TW5qIkILM1WtWgrVZz', auth: 'yYNfW8ynVO18L1TW5qIkILM1WtWgrVZz',
option: 'all' option: 'all'
} }
res.setHeader("Cache-Control", "public, max-age=20");
// установка кэша при отдачи json данных
//res.setHeader("Cache-Control", "public, max-age=20");
if (req.query.auth === queryOptions.auth) { if (req.query.auth === queryOptions.auth) {
if (req.query.option === queryOptions.option) { if (req.query.option === queryOptions.option) {
MongoClient.connect(`mongodb://localhost:27017/${dbName}`, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, db) => {
if (err) throw err;
const dbo = db.db(dbName);
dbo.collection('storeInfo').find().toArray((err, result) => { dbo.collection('storeInfo').find().toArray((err, result) => {
if (err) throw err; if (err) throw err;
res.send(result[0].items); res.send(result[0].items);
db.close();
}) })
});
} else if (!req.query.option && req.query.category) {
MongoClient.connect(`mongodb://localhost:27017/${dbName}`, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, db) => {
if (err) throw err;
const dbo = db.db(dbName); } else if (!req.query.option && req.query.category) {
dbo.collection('storeInfo').find().toArray((err, result) => { dbo.collection('storeInfo').find().toArray((err, result) => {
if (err) throw err; if (err) throw err;
const query = result[0].items[req.query.category] const query = result[0].items[req.query.category]
@ -92,38 +44,28 @@ const routes = {
} else { } else {
res.send('Товары в этой категории не найдены или такой категории нет') res.send('Товары в этой категории не найдены или такой категории нет')
} }
db.close();
}) })
});
} else { } else {
res.send('Запрос неверный'); res.send('Запрос неверный');
} }
} else { } else {
res.send('Неверный токен'); res.send('Неверный токен');
} }
},
// OnePageItem
onePageItem: function (req, res) {
const query = {
id: req.params.id
} }
MongoClient.connect(`mongodb://localhost:27017/${dbName}`, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, db) => {
if (err) throw err;
function onePageItemRoute(req, res, db) {
const dbo = db.db(dbName); const dbo = db.db(dbName);
dbo.collection('storeInfo').find().toArray((err, result) => { dbo.collection('storeInfo').find().toArray((err, result) => {
if (err) throw err; if (err) throw err;
const items = result[0].items; const items = result[0].items;
const keys = Object.keys(result[0].items); const keys = Object.keys(result[0].items);
let itemFind = false;
keys.forEach(key => { keys.forEach(key => {
items[key].forEach(item => { items[key].forEach(item => {
if (item._id != undefined) { if (item._id != undefined) {
if (item._id == query.id) { if (item._id == req.params.id) {
itemFind = true;
res.render('product', { res.render('product', {
title: item.title, title: item.title,
image: item.image, image: item.image,
@ -135,20 +77,42 @@ const routes = {
} }
} }
}) })
})
db.close();
})
}); });
if (!itemFind) res.send('Error 404');
} })
} }
module.exports = function (server) { function howToBuyRoute(req, res, db) {
server.get('/', routes.indexRoute); res.render('how-to-buy', {
server.get('/how-to-buy', routes.howToBuyRoute); pageName: 'how-to-buy'
server.get('/contacts', routes.contactsRoute); });
server.get('/comments', routes.commentsRoute); }
server.get('/my-orders', routes.myOrdersRoute);
server.get('/product/:id', routes.onePageItem); function contactsRoute(req, res, db) {
server.get('/store-api', routes.getItemsRoute); res.render('contacts', {
pageName: 'contacts'
});
}
function commentsRoute(req, res, db) {
res.render('comments', {
pageName: 'comments'
});
}
function myOrdersRoute(req, res, db) {
res.render('my-orders', {
pageName: 'my-orders'
});
}
module.exports = function (server, db) {
server.get('/', (req, res) => indexRoute(req, res, db));
server.get('/how-to-buy', (req, res) => howToBuyRoute(req, res, db));
server.get('/contacts', (req, res) => contactsRoute(req, res, db));
server.get('/comments', (req, res) => commentsRoute(req, res, db));
server.get('/my-orders', (req, res) => myOrdersRoute(req, res, db));
server.get('/product/:id', (req, res) => onePageItemRoute(req, res, db));
server.get('/store-api', (req, res) => getItemsRoute(req, res, db));
} }

View File

@ -1,16 +1,25 @@
const MongoClient = require('mongodb').MongoClient;
const db = require('./database');
const express = require('express'); const express = require('express');
const server = express(); const server = express();
const path = require('path'); const path = require('path');
MongoClient.connect(db.url, {useNewUrlParser: true, useUnifiedTopology: true}, (err, database) => {
if (err) return console.log(err)
// Pug config // Pug config
server.use(express.static(path.join(__dirname, '../dist/public'))); server.use(express.static(path.join(__dirname, '../dist/public')));
// server.use('/css', express.static(__dirname + '../dist/public/css')); // server.use('/css', express.static(__dirname + '../dist/public/css'));
server.set('view engine', 'pug'); server.set('view engine', 'pug');
server.set('views', path.join(__dirname, '../dist/views')); server.set('views', path.join(__dirname, '../dist/views'));
require('./routes/routes')(server); require('./routes/routes')(server, database);
// 404 Redirect // 404 Redirect
server.use((req, res) => res.status(404).send('Error 404')); server.use((req, res) => res.status(404).send('Error 404'));
server.listen(3000, () => console.log('Listen port 3000...')); server.listen(3000, () => console.log('Listen port 3000...'));
})

View File

@ -34,7 +34,11 @@
width: 100%; width: 100%;
} }
} }
@media (min-width: 768px) {
.items .items-list__info {
min-width: 435px;
}
}
@media (max-width: 768px) { @media (max-width: 768px) {
.items .items-list { .items .items-list {
flex-wrap: wrap; flex-wrap: wrap;

View File

@ -435,7 +435,6 @@ footer .container {
.items-list__info { .items-list__info {
margin-top: 5px; margin-top: 5px;
min-width: 435px;
} }
.list-icon, .list-icon,

File diff suppressed because one or more lines are too long

14
package-lock.json generated
View File

@ -1261,15 +1261,6 @@
} }
} }
}, },
"axios-cache-adapter": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/axios-cache-adapter/-/axios-cache-adapter-2.5.0.tgz",
"integrity": "sha512-YcMPdMoqmSLoZx7A5YD/PdYGuX6/Y9M2tHBhaIXvXrPeGgNnbW7nb3+uArWlT53WGHLfclnu2voMmS7jGXVg6A==",
"requires": {
"cache-control-esm": "1.0.0",
"lodash": "^4.17.11"
}
},
"babel-loader": { "babel-loader": {
"version": "8.0.6", "version": "8.0.6",
"resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.0.6.tgz", "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.0.6.tgz",
@ -1659,11 +1650,6 @@
"unset-value": "^1.0.0" "unset-value": "^1.0.0"
} }
}, },
"cache-control-esm": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/cache-control-esm/-/cache-control-esm-1.0.0.tgz",
"integrity": "sha512-Fa3UV4+eIk4EOih8FTV6EEsVKO0W5XWtNs6FC3InTfVz+EjurjPfDXY5wZDo/lxjDxg5RjNcurLyxEJBcEUx9g=="
},
"camelcase": { "camelcase": {
"version": "5.3.1", "version": "5.3.1",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",

View File

@ -21,7 +21,6 @@
"dependencies": { "dependencies": {
"@babel/polyfill": "^7.7.0", "@babel/polyfill": "^7.7.0",
"axios": "^0.19.0", "axios": "^0.19.0",
"axios-cache-adapter": "^2.5.0",
"express": "^4.17.1", "express": "^4.17.1",
"mongodb": "^3.3.4", "mongodb": "^3.3.4",
"pug": "^2.0.4" "pug": "^2.0.4"

View File

@ -41,6 +41,6 @@ async function buttonHandler(e) {
} }
function activeLink(e) { function activeLink(e) {
e.target.parentNode.parentNode.querySelectorAll('li a').forEach(li => li.classList.remove('active')); Array.from(e.target.parentNode.parentNode.querySelectorAll('li a')).forEach(li => li.classList.remove('active'));
e.target.classList.add('active'); e.target.classList.add('active');
} }