Skip to content

Commit 98e0e51

Browse files
committed
Upvote and Downvotes fixed
1 parent c7faa20 commit 98e0e51

File tree

6 files changed

+131
-129
lines changed

6 files changed

+131
-129
lines changed

backend/app.js

+13-3
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,20 @@ app.use(express.static('uploads'));
1515
// Set security headers
1616
app.use(helmet());
1717

18+
// cookie
19+
app.use(cookieParser());
20+
1821
// CORS
19-
app.use(cors());
22+
// app.use(cors());
23+
app.use(cors({credentials:true,origin:process.env.FRONTEND_URL}));
24+
25+
app.use(function(req, res, next) {
26+
res.header('Access-Control-Allow-Credentials', true);
27+
res.header('Access-Control-Allow-Origin', process.env.FRONTEND_URL);
28+
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,UPDATE,OPTIONS');
29+
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
30+
next();
31+
});
2032

2133
// Body Parser
2234
app.use(express.json({ limit: '50mb' }));
@@ -25,8 +37,6 @@ app.use(express.urlencoded({ limit: '50mb', extended: true }));
2537
// Response time
2638
app.use(responseTime({ suffix: false }));
2739

28-
// cookie
29-
app.use(cookieParser());
3040

3141
// Use routes
3242
app.use('/', routes);

backend/app/models/question.js

+4
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ const questionSchema = new Schema(
2525
type: Number,
2626
default: 0,
2727
},
28+
downvotes:{
29+
type:Number,
30+
default:0
31+
}
2832
},
2933
{ timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' } }
3034
);

backend/app/routes/Q&A/question/downvoteQuestion.js

+6-20
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,11 @@ const { getVoteCookieName } = require('../../../../helpers/middlewares/cookie');
66

77
module.exports = async (req, res, next) => {
88
const { questionId } = req.body;
9-
const [err] = await to(
10-
question.updateOne({ _id: questionId }, [
11-
{
12-
$set: {
13-
upvotes: {
14-
$cond: [
15-
{
16-
$gt: ['$upvotes', 0],
17-
},
18-
{
19-
$subtract: ['$upvotes', 1],
20-
},
21-
0,
22-
],
23-
},
24-
},
25-
},
26-
])
27-
);
9+
const existingQues=await question.findById(questionId)
10+
if(!existingQues.downvotes){
11+
const [err] = await to(question.updateOne({ _id: questionId },{$set:{downvotes:0}}));
12+
}
13+
const [err] = await to(question.updateOne({ _id: questionId }, { $inc: { downvotes: 1 } }));
2814
if (err) {
2915
console.log(err);
3016
const error = new ErrorHandler(constants.ERRORS.DATABASE, {
@@ -36,7 +22,7 @@ module.exports = async (req, res, next) => {
3622
return next(error);
3723
}
3824

39-
res.cookie(getVoteCookieName('question', questionId), true, { maxAge: 20 * 365 * 24 * 60 * 60 * 1000 });
25+
res.cookie(getVoteCookieName('question', questionId), true, { maxAge: 20 * 365 * 24 * 60 * 60 * 1000, sameSite: "none", secure: true });
4026
res.status(200).send({
4127
message: 'Question has been down voted',
4228
});

backend/app/routes/Q&A/question/upvoteQuestion.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ module.exports = async (req, res, next) => {
1616
return next(error);
1717
}
1818

19-
res.cookie(getVoteCookieName('question', questionId), true, { maxAge: 20 * 365 * 24 * 60 * 60 * 1000 });
19+
res.cookie(getVoteCookieName('question', questionId), true, { maxAge: 20 * 365 * 24 * 60 * 60 * 1000,sameSite:"none",secure:true });
2020

2121
res.status(200).send({
2222
message: 'Question has been upvoted',

frontend/src/pages/Q&A/Q&A.jsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ function Ques(props) {
191191
className="vote-btn"
192192
onClick={() => handleDownvote(item._id)}
193193
>
194-
👎 {item?.downvote}
194+
👎 {item?.downvotes}
195195
</button>
196196
</div>
197197
</div>

frontend/src/service/Faq.jsx

+106-104
Original file line numberDiff line numberDiff line change
@@ -2,127 +2,127 @@ import { END_POINT } from "../config/api";
22
import { showToast } from "./toastService";
33

44
export async function postFaq(formData, setToast, toast) {
5-
try {
6-
const response = await fetch(`${END_POINT}/faq/postFaq`, {
7-
method: "POST",
8-
headers: {
9-
"Content-Type": "application/json",
10-
Authorization: `Bearer ${localStorage.getItem("token")}`,
11-
},
12-
body: JSON.stringify(formData),
5+
try {
6+
const response = await fetch(`${END_POINT}/faq/postFaq`, {
7+
method: "POST",
8+
headers: {
9+
"Content-Type": "application/json",
10+
Authorization: `Bearer ${localStorage.getItem("token")}`,
11+
},
12+
body: JSON.stringify(formData),
13+
});
14+
15+
if (response.ok) {
16+
setToast({
17+
...toast,
18+
toastMessage: "FAQ has been added",
19+
toastStatus: true,
20+
toastType: "success",
1321
});
14-
15-
if (response.ok) {
16-
setToast({
17-
...toast,
18-
toastMessage: "FAQ has been added",
19-
toastStatus: true,
20-
toastType: "success",
21-
});
22-
return { success: true };
23-
} else {
24-
setToast({
25-
...toast,
26-
toastMessage: "Database Error",
27-
toastStatus: true,
28-
toastType: "error",
29-
});
30-
return { success: false, error: "Database Error" };
31-
}
32-
} catch (error) {
22+
return { success: true };
23+
} else {
3324
setToast({
3425
...toast,
35-
toastMessage: "Network Error",
26+
toastMessage: "Database Error",
3627
toastStatus: true,
3728
toastType: "error",
3829
});
39-
return { success: false, error: "Network Error" };
30+
return { success: false, error: "Database Error" };
4031
}
32+
} catch (error) {
33+
setToast({
34+
...toast,
35+
toastMessage: "Network Error",
36+
toastStatus: true,
37+
toastType: "error",
38+
});
39+
return { success: false, error: "Network Error" };
4140
}
41+
}
4242

4343
export async function getFaq() {
44-
try {
45-
const response = await fetch(`${END_POINT}/faq/getFaq`);
46-
if (!response.ok) {
47-
throw new Error("Failed to fetch FAQs");
48-
}
49-
const data = await response.json();
50-
return data.Faq;
51-
} catch (error) {
52-
console.error("Failed to fetch FAQs:", error.message);
44+
try {
45+
const response = await fetch(`${END_POINT}/faq/getFaq`);
46+
if (!response.ok) {
5347
throw new Error("Failed to fetch FAQs");
5448
}
49+
const data = await response.json();
50+
return data.Faq;
51+
} catch (error) {
52+
console.error("Failed to fetch FAQs:", error.message);
53+
throw new Error("Failed to fetch FAQs");
54+
}
5555
}
5656

57-
export const deleteFaq = async (faqId, setToast, toast) => {
58-
const url = `${END_POINT}/faq/deleteFaq`;
59-
const body = { faqId: faqId };
60-
const headers = {
61-
"Content-Type": "application/json",
62-
authorization: `Bearer ${localStorage.getItem("token")}`,
63-
};
64-
try {
65-
const response = await fetch(url, {
66-
method: "PUT",
67-
headers: headers,
68-
body: JSON.stringify(body),
69-
});
70-
if (!response.ok) {
71-
throw new Error(`HTTP error! status: ${response.status}`);
72-
}
73-
const data = await response.json();
74-
setToast({
75-
...toast,
76-
toastMessage: data.message,
77-
toastStatus: true,
78-
toastType: "success",
79-
});
80-
return data.message;
81-
} catch (error) {
82-
console.error("Failed to delete FAQ:", error.message);
83-
setToast({
84-
...toast,
85-
toastMessage: "Failed to delete FAQ",
86-
toastStatus: true,
87-
toastType: "error",
88-
});
89-
throw new Error("Failed to delete FAQ");
57+
export const deleteFaq = async (faqId, setToast, toast) => {
58+
const url = `${END_POINT}/faq/deleteFaq`;
59+
const body = { faqId: faqId };
60+
const headers = {
61+
"Content-Type": "application/json",
62+
authorization: `Bearer ${localStorage.getItem("token")}`,
63+
};
64+
try {
65+
const response = await fetch(url, {
66+
method: "PUT",
67+
headers: headers,
68+
body: JSON.stringify(body),
69+
});
70+
if (!response.ok) {
71+
throw new Error(`HTTP error! status: ${response.status}`);
9072
}
73+
const data = await response.json();
74+
setToast({
75+
...toast,
76+
toastMessage: data.message,
77+
toastStatus: true,
78+
toastType: "success",
79+
});
80+
return data.message;
81+
} catch (error) {
82+
console.error("Failed to delete FAQ:", error.message);
83+
setToast({
84+
...toast,
85+
toastMessage: "Failed to delete FAQ",
86+
toastStatus: true,
87+
toastType: "error",
88+
});
89+
throw new Error("Failed to delete FAQ");
90+
}
9191
};
9292

9393
export const updateFaq = async (faqId, updatedFaqDetails, setToast, toast) => {
94-
try {
95-
const response = await fetch(`${END_POINT}/faq/updateFaq`, {
96-
method: "PATCH",
97-
headers: {
98-
"Content-Type": "application/json",
99-
authorization: `Bearer ${localStorage.getItem("token")}`,
100-
},
101-
body: JSON.stringify({ faqId, ...updatedFaqDetails }),
102-
});
103-
104-
if (!response.ok) {
105-
throw new Error("Failed to update FAQ");
106-
}
94+
try {
95+
const response = await fetch(`${END_POINT}/faq/updateFaq`, {
96+
method: "PATCH",
97+
headers: {
98+
"Content-Type": "application/json",
99+
authorization: `Bearer ${localStorage.getItem("token")}`,
100+
},
101+
body: JSON.stringify({ faqId, ...updatedFaqDetails }),
102+
});
107103

108-
const data = await response.json();
109-
setToast({
110-
...toast,
111-
toastMessage: data.message,
112-
toastStatus: true,
113-
toastType: "success",
114-
});
115-
return data.message;
116-
} catch (error) {
117-
console.error("Failed to update FAQ:", error.message);
118-
setToast({
119-
...toast,
120-
toastMessage: "Failed to update FAQ",
121-
toastStatus: true,
122-
toastType: "error",
123-
});
124-
throw new Error("Failed to update FAQ");
104+
if (!response.ok) {
105+
throw new Error("Failed to update FAQ");
125106
}
107+
108+
const data = await response.json();
109+
setToast({
110+
...toast,
111+
toastMessage: data.message,
112+
toastStatus: true,
113+
toastType: "success",
114+
});
115+
return data.message;
116+
} catch (error) {
117+
console.error("Failed to update FAQ:", error.message);
118+
setToast({
119+
...toast,
120+
toastMessage: "Failed to update FAQ",
121+
toastStatus: true,
122+
toastType: "error",
123+
});
124+
throw new Error("Failed to update FAQ");
125+
}
126126
};
127127

128128
export const getAllQuestions = async (setToast, toast) => {
@@ -292,6 +292,7 @@ export const upvote = async (questionId, handleToast) => {
292292
headers: {
293293
"Content-Type": "application/json",
294294
},
295+
credentials: "include",
295296
body: JSON.stringify({ questionId }),
296297
});
297298
if (!response.ok) {
@@ -300,7 +301,7 @@ export const upvote = async (questionId, handleToast) => {
300301
showToast(handleToast, "Upvote Successfully");
301302
return response.json();
302303
} catch (error) {
303-
showToast(handleToast, "Failed to upvote question", "error");
304+
showToast(handleToast, "You have already voted", "error");
304305
throw new Error("Failed to upvote question");
305306
}
306307
};
@@ -312,6 +313,7 @@ export const downvote = async (questionId, handleToast) => {
312313
headers: {
313314
"Content-Type": "application/json",
314315
},
316+
credentials: "include",
315317
body: JSON.stringify({ questionId }),
316318
});
317319
if (!response.ok) {
@@ -320,7 +322,7 @@ export const downvote = async (questionId, handleToast) => {
320322
showToast(handleToast, "Downvote Successfully");
321323
return response.json();
322324
} catch (error) {
323-
showToast(handleToast, "Failed to downvote question", "error");
325+
showToast(handleToast, "You have already voted", "error");
324326
throw new Error("Failed to downvote question");
325327
}
326-
};
328+
};

0 commit comments

Comments
 (0)