Commit 2c21f1d4 authored by Egor Kremnev's avatar Egor Kremnev

add mongoose

parent 6667ac63
......@@ -4,5 +4,9 @@ const rootPath = __dirname;
module.exports = {
rootPath,
port: 8001,
uploadPath: path.join(rootPath, 'public', 'uploads')
uploadPath: path.join(rootPath, 'public', 'uploads'),
db: {
host: 'mongodb://localhost',
database: 'shop',
}
};
const fs = require('fs');
const fileName = './db/db.json';
let data = [];
module.exports = {
init() {
try {
const content = fs.readFileSync(fileName);
data = JSON.parse(content.toString());
} catch (e) {
}
},
getItems() {
return data;
},
getItem(id) {
return data.find(item => item.id === id);
},
addItem(item) {
data.push(item);
this.save();
},
save() {
fs.writeFileSync(fileName, JSON.stringify(data));
}
};
const cors = require('cors');
const express = require('express');
const app = express();
const {port} = require('./config');
const {port, db: dbConfig} = require('./config');
const createProductsRoutes = require('./routes/products');
const fileDb = require('./db/fileDb');
fileDb.init();
const mongoose = require('mongoose');
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
app.use('/api/v1/products', createProductsRoutes(fileDb));
app.use('/api/v1/products', createProductsRoutes());
const run = async () => {
await mongoose.connect(
dbConfig.host + '/' + dbConfig.database,
{useNewUrlParser: true}
);
app.listen(port, () => {
console.log("Server running at http://localhost:" + port);
});
process.on('exit', () => {
mongoose.disconnect();
});
};
app.listen(port, () => {
console.log("Server running at http://localhost:" + port);
});
run().catch(e => console.error(e));
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProductSchema = new Schema({
title: {
required: true,
type: String
},
price: {
required: true,
type: Number
},
description: String,
image: String
});
const Product = mongoose.model('Product', ProductSchema);
module.exports = Product;
This diff is collapsed.
......@@ -15,6 +15,8 @@
"cors": "^2.8.5",
"express": "^4.18.2",
"fix-esm": "^1.0.1",
"mongodb": "^5.3.0",
"mongoose": "^7.0.4",
"multer": "^1.4.5-lts.1",
"nanoid": "^4.0.2"
},
......
......@@ -4,6 +4,7 @@ const {nanoid} = require('fix-esm').require('nanoid');
const multer = require('multer');
const path = require('path');
const {uploadPath} = require('./../config');
const Product = require('../models/Product');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
......@@ -16,25 +17,44 @@ const storage = multer.diskStorage({
const upload = multer({storage});
const createRoutes = (db) => {
router.post('/', upload.single('image'), (req, res) => {
const item = {...req.body, id: nanoid()};
const createRoutes = () => {
router.post('/', upload.single('image'), async (req, res) => {
const productData = {...req.body};
if (req.file) item.image = req.file.filename;
if (req.file) productData.image = req.file.filename;
else productData.image = null;
db.addItem(item);
res.send(item);
try {
const product = new Product(productData);
res
.status(201)
.send(await product.save());
} catch (e) {
res
.status(400)
.send(e);
}
});
router.get('/', (req, res) => {
res.send(db.getItems());
router.get('/', async (req, res) => {
try {
res.send(await Product.find());
} catch (e) {
res.sendStatus(500);
}
});
router.get('/:id', (req, res) => {
const item = db.getItem(req.params.id);
router.get('/:id', async (req, res) => {
try {
const result = await Product.findById(req.params.id);
if (result) return res.send(result);
if (item) res.send(item);
res.sendStatus(404);
res.sendStatus(404);
} catch (e) {
res.sendStatus(500);
}
});
return router;
......
......@@ -25,7 +25,7 @@ const ProductItem = ({product}) => {
</strong>
</CardContent>
<CardActions>
<IconButton component={Link} to={PRODUCT_VIEW.replace(':id', product.id)}>
<IconButton component={Link} to={PRODUCT_VIEW.replace(':id', product._id)}>
<ArrowForwardIosIcon/>
</IconButton>
</CardActions>
......
......@@ -44,7 +44,7 @@ const Products = () => {
{
products.map(product => (
<ProductItem
key={product.id}
key={product._id}
product={product}
/>
))
......
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