#4, добавила роутер /products

parent 7ee45ded
const express = require("express");
const multer = require("multer");
const path = require("path");
const {nanoid} = require("nanoid");
const config = require("../config");
const Product = require("../models/Product");
const auth = require("../middleware/auth");
const router = express.Router();
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, config.uploadPath);
},
filename: (req, file, cb) => {
cb(null, nanoid() + path.extname(file.originalname));
}
});
const upload = multer({storage});
const createRouter = () => {
router.get("/", async (req, res) => {
let category;
if (req.query.category) {
category = {category: req.query.category};
}
try {
const products = await Product.find(category).populate("category", "title");
res.send(products);
} catch (e) {
res.sendStatus(500);
}
});
router.get("/:id", async (req, res) => {
const product = await Product.findById(req.params.id).populate("category");
res.send(product);
});
router.post("/", [upload.single("image"), auth], async (req, res) => {
const product = new Product(req.body);
if (req.file) {
product.image = req.file.filename;
}
await product.save();
res.send(product);
});
router.delete("/:id", async (req, res) => {
try {
res.send(await Product.findByIdAndRemove(req.params.id));
} catch(e) {res.status(500).send(e)}
});
return router;
};
module.exports = createRouter;
...@@ -32,9 +32,7 @@ const createRouter = () => { ...@@ -32,9 +32,7 @@ const createRouter = () => {
} }
user.generateToken(); user.generateToken();
await user.save(); await user.save();
res.send(user); res.send(user);
}); });
...@@ -50,7 +48,7 @@ const createRouter = () => { ...@@ -50,7 +48,7 @@ const createRouter = () => {
if (!user) return res.send(success); if (!user) return res.send(success);
user.generateToken(); user.generateToken();
await user.save() await user.save();
res.send(success); res.send(success);
......
...@@ -6,7 +6,7 @@ module.exports = { ...@@ -6,7 +6,7 @@ module.exports = {
rootPath, rootPath,
uploadPath: path.join(rootPath, "public", "uploads"), uploadPath: path.join(rootPath, "public", "uploads"),
db: { db: {
name: "shop", name: "store",
url: "mongodb://localhost" url: "mongodb://localhost"
} }
}; };
...@@ -12,7 +12,7 @@ app.use(cors()); ...@@ -12,7 +12,7 @@ app.use(cors());
app.use(express.static("public")); app.use(express.static("public"));
app.use(express.json()); app.use(express.json());
mongoose.connect(`${config.db.url}/${config.db.name}`, {useNewUrlParser: true}) mongoose.connect(`${config.db.url}/${config.db.name}`, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true,})
.then(() => { .then(() => {
console.log("Mongoose connected!"); console.log("Mongoose connected!");
app.use("/products", products()); app.use("/products", products());
......
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