diff --git a/controllers/reviewController.js b/controllers/reviewController.js new file mode 100644 index 0000000..6a89b69 --- /dev/null +++ b/controllers/reviewController.js @@ -0,0 +1,46 @@ +const Review = require("../models/reviewModel"); +const JWT = require("../utilities/jwt"); +const { verifyAuthorization } = require("../utilities/verifyAuthorization"); +const ReviewFactory = require("../utilities/ReviewFactory"); + +module.exports.addReview = async (req, res) => { + if (!verifyAuthorization(req.headers, ["NORMAL", "ADMIN"])) { + return res.status(403).json({ + message: "Unauthorized", + }); + } + + let { uid } = JWT.verify(req.headers.authorization); + + let review = ReviewFactory.createReview({ ...req.body, user: uid }); + + try { + await review.save(); + res.status(200).json({ + message: "Review added successfully", + data: review, + }); + } catch (error) { + res.status(500).json({ + message: "Something went while adding your review", + }); + } +}; + +module.exports.getProductReviews = (req, res) => { + let productId = req.params.product_id; + + Review.find({ product: productId }) + .populate("user") + .exec((err, reviews) => { + if (err) { + return res.status(400).json({ + message: "Something went wrong with getting the reviews", + }); + } + return res.status(200).json({ + message: "Retrieved reviews successfully", + data: reviews, + }); + }); +}; diff --git a/index.js b/index.js index 7f3b627..5f49f95 100644 --- a/index.js +++ b/index.js @@ -10,6 +10,7 @@ let authRoutes = require("./routes/auth"); let productRoutes = require("./routes/prouductRoutes"); let userRoutes = require("./routes/users"); let orderRoutes = require("./routes/orderRoutes"); +let reviewRoutes = require("./routes/reviewRoutes"); const app = express(); @@ -33,6 +34,7 @@ app.use("/", authRoutes); app.use("/", userRoutes); app.use("/products", productRoutes); app.use("/orders", orderRoutes); +app.use("/reviews", reviewRoutes); const mongo = mongoose.connect(process.env.DB_PATH, config.DB_OPTIONS); diff --git a/routes/reviewRoutes.js b/routes/reviewRoutes.js new file mode 100644 index 0000000..e3bc131 --- /dev/null +++ b/routes/reviewRoutes.js @@ -0,0 +1,11 @@ +const { + addReview, + getProductReviews, +} = require("../controllers/reviewController"); + +let router = require("express").Router(); + +router.post("/", addReview); +router.get("/:product_id", getProductReviews); + +module.exports = router; diff --git a/utilities/ReviewFactory.js b/utilities/ReviewFactory.js new file mode 100644 index 0000000..a485a27 --- /dev/null +++ b/utilities/ReviewFactory.js @@ -0,0 +1,12 @@ +const Review = require("../models/reviewModel"); +const { updateEntity } = require("./updateEntity"); + +class ReviewFactory { + static createReview(body) { + let review = new Review(); + updateEntity(review, body); + return review; + } +} + +module.exports = ReviewFactory;