Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] post testimonials backend Fixed #1056

Merged
merged 3 commits into from
Jun 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 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);

Check failure

Code scanning / CodeQL

Missing rate limiting High test

This route handler performs
authorization
, but is not rate-limited.
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: "",
Hemu21 marked this conversation as resolved.
Show resolved Hide resolved
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;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Kajol-Kumari This is the function we used to get data. here I made small chage if image exist. we use that url else we use default image a url.

});
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}
Loading