Skip to content

Commit

Permalink
πŸ€ [BUG] post testimonials backend Fixed (#1056)
Browse files Browse the repository at this point in the history
* Fixed

* Update AddTestimonial.jsx

* Update Testimonial.jsx
  • Loading branch information
Hemu21 authored Jun 20, 2024
1 parent ed6ac50 commit a9ddf03
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 12 deletions.
2 changes: 1 addition & 1 deletion backend/app/models/Testimonial.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const testimonialSchema = new Schema(
},
image: {
type: String,
required: true,
default: null,
},
text: {
type: String,
Expand Down
18 changes: 17 additions & 1 deletion backend/app/routes/testimonial/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
const router = require('express').Router({ mergeParams: true });
const multer = require('multer');
const { nanoid } = require('nanoid');
const path = require('path');
const validationMiddleware = require('../../../helpers/middlewares/validation');
const { authMiddleware } = require('../../../helpers/middlewares/auth');

Expand All @@ -7,7 +10,20 @@ const postTestimonial = require('./postTestimonial');
const getTestimonials = require('./getTestimonials');
const deleteTestimonial = require('./deleteTestimonial');

router.post('/', validationMiddleware(postTestimonialValidationSchema), authMiddleware, postTestimonial);
const store = multer.diskStorage({
destination: (req, file, cb) => {
const dir = 'uploads/TestimonialProfile/';
cb(null, dir);
},
filename: (req, file, cb) => {
const uniqueFilename = nanoid() + path.extname(file.originalname);
console.log(`Generated filename: ${uniqueFilename}`);
cb(null, uniqueFilename);
},
});
const upload = multer({ storage: store });

router.post('/', authMiddleware, upload.single('image'), postTestimonial);
router.get('/getTestimonials', getTestimonials);
router.delete('/:id', authMiddleware, deleteTestimonial);

Expand Down
2 changes: 1 addition & 1 deletion backend/app/routes/testimonial/postTestimonial.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { ErrorHandler } = require('../../../helpers/error');
const constants = require('../../../constants');

module.exports = async (req, res, next) => {
const [err, { _id }] = await to(Testimonial.create({ ...req.body }));
const [err, { _id }] = await to(Testimonial.create({ ...req.body, image: req.file?.path }));
if (err) {
const error = new ErrorHandler(constants.ERRORS.DATABASE, {
statusCode: 500,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function AddTestimonial() {
name: "",
position: "",
company: "",
image: "https://i.pinimg.com/originals/f4/cd/d8/f4cdd85c50e44aa59a303fb163ff90f8.jpg",
image: "",
text: "",
rating: "",
});
Expand All @@ -27,7 +27,7 @@ export function AddTestimonial() {
name: Joi.string().required().label("Name"),
position: Joi.string().required().label("Position"),
company: Joi.string().required().label("Company"),
image: Joi.any().required().label("Image"),
image: Joi.any().optional().label("Image"),
text: Joi.string().required().label("Text"),
rating: Joi.number().required().min(1).max(5).label("Rating"),
};
Expand Down Expand Up @@ -55,6 +55,7 @@ export function AddTestimonial() {

if (files && files[0]) {
setPic(files[0]);
setFormData({ ...formData, image: files[0] });
let reader = new FileReader();
reader.onload = function (e) {
setPicUrl(e.target.result);
Expand Down Expand Up @@ -96,17 +97,25 @@ export function AddTestimonial() {
console.log(errors);
} else {
// Call the server
await addTestimonial(formData, setToast, toast);
const form = new FormData();
form.append("name", formData.name);
form.append("position", formData.position);
form.append("company", formData.company);
form.append("text", formData.text);
form.append("rating", formData.rating);
form.append("image", formData.image);

await addTestimonial(form, setToast, toast);

const temp = {
...formData,
name: "",
position: "",
company: "",
text: "",
rating: "",
};
setFormData(temp);
setPicUrl("./images/testimonialImg.png");
}
return pic;
};
Expand All @@ -124,6 +133,7 @@ export function AddTestimonial() {
<form
className={styles["inside-add-testimonial"]}
onSubmit={onSubmit}
enctype="multipart/form-data"
>
<Grid container>
<Grid xs={12} sm={2} md={3} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export function ManageTestimonial() {
<div className={style["crd"]} key={index}>
<div>
<img
src={testimonial.image || "./images/defaultUser.png"}
src={testimonial.image}
className={style["image"]}
alt=""
/>
Expand Down
20 changes: 16 additions & 4 deletions frontend/src/service/Testimonial.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,20 @@ async function getTestimonials(setTestimonials, setToast) {

if (response.ok) {
const data = await response.json();
setTestimonials(data);
let _data = [...data]
await data?.map((item,index) => {
let formattedPath = item.image?.replace(/\\/g, "/");
if (formattedPath?.startsWith("uploads/")) {
formattedPath = formattedPath.replace("uploads/", "");
if (formattedPath) {
formattedPath = `${END_POINT}/${formattedPath}`;
}
}else{
formattedPath = "./images/testimonialImg.png";
}
_data[index].image = formattedPath;
});
setTestimonials(_data);
// we won't be showing the success message for this as it looks wierd on the home page.
} else {
showToast(setToast, "Failed to fetch testimonials.", "error");
Expand Down Expand Up @@ -58,10 +71,9 @@ const addTestimonial = async (testimonial, setToast,toast) => {
const response = await fetch(`${END_POINT}/testimonials/`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: JSON.stringify(testimonial),
body: testimonial,
});
const res = await response.json();
if (!response.ok) {
Expand All @@ -86,4 +98,4 @@ const addTestimonial = async (testimonial, setToast,toast) => {
}


export { getTestimonials, addTestimonial, deleteTestimonial}
export { getTestimonials, addTestimonial, deleteTestimonial}

0 comments on commit a9ddf03

Please sign in to comment.