Commit 4481e41e authored by Vadim's avatar Vadim

конец занятия №80

parent 61c9d8bb
...@@ -3,5 +3,11 @@ const rootPath = __dirname; ...@@ -3,5 +3,11 @@ const rootPath = __dirname;
module.exports = { module.exports = {
rootPath, rootPath,
uploadPath: path.join(rootPath, '../public/uploads') uploadPath: path.join(rootPath, '../public/uploads'),
db: {
host: 'localhost',
user: 'user',
password: 'user',
database: 'shop'
}
}; };
\ No newline at end of file
module.exports = (db) => ({
getItems(entity){
return new Promise((res, rej) => {
db.query("SELECT * FROM ??", [entity], (err, result)=> {
if(err) {
rej(err)
}
res(result);
})
});
},
getItem(entity, id){
return new Promise((res, rej) => {
db.query("SELECT * FROM ?? WHERE id = ?", [entity, id], (err, result)=> {
if(err) {
rej(err)
}
res(result);
})
});
},
addItem(entity, data){
return new Promise((res, rej) => {
db.query("INSERT INTO ?? SET ?", [entity, data], (err, result)=> {
if(err) {
rej(err)
}
data.id = result.insertId;
res(data);
})
});
}
});
\ No newline at end of file
...@@ -2,43 +2,42 @@ const express = require('express'); ...@@ -2,43 +2,42 @@ const express = require('express');
const multer = require('multer'); const multer = require('multer');
const path = require('path'); const path = require('path');
const router = express.Router(); const router = express.Router();
const db = require('./db/fileDb');
const {nanoid} = require('nanoid'); const {nanoid} = require('nanoid');
const config = require('./config') const config = require('./config');
const storage = multer.diskStorage({ const storage = multer.diskStorage({
destination: (req, file, cb) => { destination: (req, file, cb) => {
cb(null, config.uploadPath); cb(null, config.uploadPath);
}, },
filename: (req, file, cb) => { filename: (req, file, cb) => {
cb(null, nanoid() + path.extname(file.originalname)) cb(null, nanoid() + path.extname(file.originalname))
} }
}); });
const upload = multer({storage}) const upload = multer({storage});
db.init(); const createRouter = (db) => {
router.get('/', async (req, res) => {
router.get('/', (req, res) => { const products = await db.getItems('products');
const products = db.getItems(); res.send(products);
res.send(products) });
});
router.get('/:id', (req, res) => { router.get('/:id', async (req, res) => {
res.send('Single product will be here' + req.params.id) const product = await db.getItem('products', req.params.id);
}); res.send(product[0]);
});
router.post('/', upload.single('image'), (req, res) => { router.post('/', upload.single('image'), async (req, res) => {
console.log('Create product', req.body); const product = req.body;
const newProduct = {
...req.body,
_id: nanoid()
};
if(req.file) { if(req.file) {
newProduct.image = req.file.filename; product.image = req.file.filename;
} }
db.addItem(newProduct); const newProduct = await db.addItem('products', product);
res.send(newProduct) res.send(newProduct);
}); });
return router;
};
module.exports = router; module.exports = createRouter;
\ No newline at end of file \ No newline at end of file
CREATE DATABASE IF NOT EXISTS shop;
USE shop;
CREATE TABLE IF NOT EXISTS products(
`id` int NOT NULL PRIMARY KEY AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`price` decimal(6,2) NOT NULL,
`description` text(1000),
`image` varchar(30)
);
...@@ -97,6 +97,11 @@ ...@@ -97,6 +97,11 @@
"integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
"dev": true "dev": true
}, },
"bignumber.js": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz",
"integrity": "sha512-t/OYhhJ2SD+YGBQcjY8GzzDHEk9f3nerxjtfa6tlMXfe7frs/WozhvCNoGvpM0P3bNf3Gq5ZRMlGr5f3r4/N8A=="
},
"binary-extensions": { "binary-extensions": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.1.0.tgz", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.1.0.tgz",
...@@ -964,6 +969,46 @@ ...@@ -964,6 +969,46 @@
"xtend": "^4.0.0" "xtend": "^4.0.0"
} }
}, },
"mysql": {
"version": "2.18.1",
"resolved": "https://registry.npmjs.org/mysql/-/mysql-2.18.1.tgz",
"integrity": "sha512-Bca+gk2YWmqp2Uf6k5NFEurwY/0td0cpebAucFpY/3jhrwrVGuxU2uQFCHjU19SJfje0yQvi+rVWdq78hR5lig==",
"requires": {
"bignumber.js": "9.0.0",
"readable-stream": "2.3.7",
"safe-buffer": "5.1.2",
"sqlstring": "2.3.1"
},
"dependencies": {
"isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE="
},
"readable-stream": {
"version": "2.3.7",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz",
"integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==",
"requires": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"requires": {
"safe-buffer": "~5.1.0"
}
}
}
},
"nanoid": { "nanoid": {
"version": "3.1.18", "version": "3.1.18",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.18.tgz", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.18.tgz",
...@@ -1299,6 +1344,11 @@ ...@@ -1299,6 +1344,11 @@
"integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==", "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==",
"dev": true "dev": true
}, },
"sqlstring": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz",
"integrity": "sha1-R1OT/56RR5rqYtyvDKPRSYOn+0A="
},
"statuses": { "statuses": {
"version": "1.5.0", "version": "1.5.0",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
......
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.17.1", "express": "^4.17.1",
"multer": "^1.4.2", "multer": "^1.4.2",
"mysql": "^2.18.1",
"nanoid": "^3.1.18" "nanoid": "^3.1.18"
}, },
"devDependencies": { "devDependencies": {
......
const express = require('express'); const express = require('express');
const products = require('./app/products'); const products = require('./app/products');
const cors = require('cors') const cors = require('cors');
const app = express(); const mysql = require('mysql');
const config = require('./app/config');
const db = require('./app/db/mysql');
const app = express();
const port = 8000; const port = 8000;
const connection = mysql.createConnection(config.db);
const corsOptions = { const corsOptions = {
origin: 'http://localhost:3000', origin: 'http://localhost:3000',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204 optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
} };
app.use(cors(corsOptions)) app.use(cors(corsOptions));
app.use(express.json()) app.use(express.json());
app.use('/products', products); app.use(express.static('public'));
app.listen(port, () => {
connection.connect(err => {
if(err){
console.error(err);
throw err;
}
app.use('/products', products(db(connection)));
app.listen(port, () => {
console.log(`Server started on port ${port}`) console.log(`Server started on port ${port}`)
});
console.log('mysql connected!');
}); });
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment