Skip to content

Commit 4e50766

Browse files
Изменил систему рейтинга, а также добавил хуки в модель rates (#63)
* Изменил систему рейтинга, а также добавил хуки в модель rates * Удалил gen из файла gitignor. Изменения в openApi
1 parent 427b40c commit 4e50766

8 files changed

+178
-78
lines changed

openapi.yml

+18-18
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@ paths:
2525
$ref: '#/components/schemas/UserData'
2626
'401':
2727
description: 'Ошибка авторизации'
28-
'404':
29-
description: 'Не найдено'
28+
'400':
29+
description: 'Некорректный запрос'
3030
/user/favorites:
3131
get:
3232
security:
@@ -41,7 +41,7 @@ paths:
4141
'401':
4242
description: 'Ошибка авторизации'
4343
'400':
44-
description: 'Неправильный, некорректный запрос'
44+
description: 'Некорректный запрос'
4545
/user/favorites/{questionId}:
4646
post:
4747
summary: 'Добавление вопроса в избранные'
@@ -67,7 +67,7 @@ paths:
6767
'401':
6868
description: 'Ошибка авторизации'
6969
'400':
70-
description: 'Неправильный, некорректный запрос'
70+
description: 'Некорректный запрос'
7171
'404':
7272
description: 'Не найдено'
7373
delete:
@@ -94,7 +94,7 @@ paths:
9494
'401':
9595
description: 'Ошибка авторизации'
9696
'400':
97-
description: 'Неправильный, некорректный запрос'
97+
description: 'Некорректный запрос'
9898
/tags:
9999
get:
100100
summary: 'Поиск по тэгам'
@@ -118,7 +118,7 @@ paths:
118118
type: string
119119
$ref: '#/components/schemas/TagData'
120120
'400':
121-
description: 'Неправильный, некорректный запрос'
121+
description: 'Некорректный запрос'
122122
post:
123123
security:
124124
- bearerAuth: []
@@ -148,7 +148,7 @@ paths:
148148
'401':
149149
description: 'Ошибка авторизации'
150150
'400':
151-
description: 'Неправильный, некорректный запрос'
151+
description: 'Некорректный запрос'
152152
/questions:
153153
get:
154154
summary: 'Поиск по вопросам'
@@ -170,7 +170,7 @@ paths:
170170
type: string
171171
$ref: '#/components/schemas/QuestionData'
172172
'400':
173-
description: 'Неправильный, некорректный запрос'
173+
description: 'Некорректный запрос'
174174
post:
175175
security:
176176
- bearerAuth: []
@@ -211,7 +211,7 @@ paths:
211211
'401':
212212
description: 'Ошибка авторизации'
213213
'400':
214-
description: 'Неправильный, некорректный запрос'
214+
description: 'Некорректный запрос'
215215
/questions/{questionId}:
216216
get:
217217
summary: 'Вывод вопроса'
@@ -230,7 +230,7 @@ paths:
230230
schema:
231231
$ref: '#/components/schemas/QuestionData'
232232
'400':
233-
description: 'Неправильный, некорректный запрос'
233+
description: 'Некорректный запрос'
234234
delete:
235235
summary: 'Удаление вопроса'
236236
parameters:
@@ -257,7 +257,7 @@ paths:
257257
'403':
258258
description: 'Недостаточно прав доступа'
259259
'400':
260-
description: 'Неправильный, некорректный запрос'
260+
description: 'Некорректный запрос'
261261
patch:
262262
summary: 'Восстановление вопроса'
263263
parameters:
@@ -284,7 +284,7 @@ paths:
284284
'403':
285285
description: 'Недостаточно прав доступа'
286286
'400':
287-
description: 'Неправильный, некорректный запрос'
287+
description: 'Некорректный запрос'
288288
/questions/{questionId}/rate:
289289
post:
290290
summary: 'Изменение рейтинга для вопроса'
@@ -323,7 +323,7 @@ paths:
323323
'401':
324324
description: 'Ошибка авторизации'
325325
'400':
326-
description: 'Неправильный, некорректный запрос'
326+
description: 'Некорректный запрос'
327327
delete:
328328
summary: 'Удаление оценки для вопроса'
329329
parameters:
@@ -348,7 +348,7 @@ paths:
348348
'401':
349349
description: 'Ошибка авторизации'
350350
'400':
351-
description: 'Неправильный, некорректный запрос'
351+
description: 'Некорректный запрос'
352352
/questions/{questionId}/comments:
353353
get:
354354
summary: 'Вывод комментарий вопроса'
@@ -367,7 +367,7 @@ paths:
367367
schema:
368368
$ref: '#/components/schemas/CommentData'
369369
'400':
370-
description: 'Неправильный, некорректный запрос'
370+
description: 'Некорректный запрос'
371371
post:
372372
summary: 'Добавление комментарий вопроса'
373373
parameters:
@@ -404,7 +404,7 @@ paths:
404404
'401':
405405
description: 'Ошибка авторизации'
406406
'400':
407-
description: 'Неправильный, некорректный запрос'
407+
description: 'Некорректный запрос'
408408
'404':
409409
description: 'Не найдено'
410410
/questions/{questionId}/comments/{commentId}/rate:
@@ -451,7 +451,7 @@ paths:
451451
'401':
452452
description: 'Ошибка авторизации'
453453
'400':
454-
description: 'Неправильный, некорректный запрос'
454+
description: 'Некорректный запрос'
455455
delete:
456456
summary: 'Удаление оценки для комментария'
457457
parameters:
@@ -482,7 +482,7 @@ paths:
482482
'401':
483483
description: 'Ошибка авторизации'
484484
'400':
485-
description: 'Неправильный, некорректный запрос'
485+
description: 'Некорректный запрос'
486486
components:
487487
securitySchemes:
488488
bearerAuth:

src/controllers/questions.controller.js

-43
Original file line numberDiff line numberDiff line change
@@ -111,47 +111,4 @@ module.exports.questionsController = {
111111
return res.status(401).json({ error: e.toString() });
112112
}
113113
},
114-
changeRate: async (req, res) => {
115-
const { volume } = req.body;
116-
const { questionId } = req.params;
117-
118-
try {
119-
const question = await Question.findById(questionId);
120-
121-
if (!question) {
122-
return res.status(404).json({
123-
error: 'Вопрос с таким ID не найден',
124-
});
125-
}
126-
127-
let updated = false;
128-
question.rates.forEach((rate, index) => {
129-
if (rate.user.toString() === req.user.userId) {
130-
if (rate.volume !== volume) {
131-
// eslint-disable-next-line no-param-reassign
132-
rate.volume = volume;
133-
} else {
134-
question.rates.splice(index, 1);
135-
}
136-
137-
updated = true;
138-
}
139-
});
140-
141-
if (!updated) {
142-
question.rates.push({
143-
user: req.user.userId,
144-
volume,
145-
});
146-
}
147-
148-
await question.save();
149-
150-
return res.json(question.rates);
151-
} catch (e) {
152-
return res.status(401).json({
153-
error: e.toString(),
154-
});
155-
}
156-
},
157114
};

src/controllers/rates.controlle.js

+116
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
const Rate = require('../models/Rate.model');
2+
const Comment = require('../models/Comment.model');
3+
const Question = require('../models/Question.model');
4+
5+
module.exports.ratesController = {
6+
changeRate: async (req, res) => {
7+
const { volume } = req.body;
8+
const { questionId } = req.params;
9+
const { commentId } = req.params;
10+
11+
try {
12+
if (volume < -1 || volume > 1 || volume === 0) {
13+
return res.json({ message: 'Error volume' });
14+
}
15+
16+
const question = await Question.findById(questionId);
17+
const comment = await Comment.findById(commentId);
18+
19+
const checkRate = await Rate.findOne(
20+
commentId
21+
? { rateFrom: req.user.userId, ratedComment: commentId }
22+
: {
23+
rateFrom: req.user.userId,
24+
ratedQuestion: questionId,
25+
}
26+
);
27+
28+
if (!checkRate) {
29+
if (!commentId) {
30+
await Rate.create({
31+
rateFrom: req.user.userId,
32+
rateTo: question.user,
33+
volume,
34+
ratedQuestion: question._id,
35+
});
36+
return res.json({ message: 'Рейтинг успешно изменён' });
37+
}
38+
await Rate.create({
39+
rateFrom: req.user.userId,
40+
rateTo: comment.author,
41+
volume,
42+
ratedComment: comment._id,
43+
});
44+
return res.json({ message: 'Рейтинг успешно изменён' });
45+
}
46+
if (checkRate.volume !== volume) {
47+
if (!commentId) {
48+
await Question.findByIdAndUpdate(questionId, {
49+
questionRateCount: question.questionRateCount + volume,
50+
});
51+
await Rate.findOneAndUpdate(
52+
{
53+
rateFrom: req.user.userId,
54+
ratedQuestion: questionId,
55+
},
56+
{ volume }
57+
);
58+
return res.json({ message: 'Рейтинг успешно изменён' });
59+
}
60+
await Comment.findByIdAndUpdate(commentId, {
61+
commentRateCount: comment.commentRateCount + volume,
62+
});
63+
await Rate.findOneAndUpdate(
64+
{
65+
rateFrom: req.user.userId,
66+
ratedComment: commentId,
67+
},
68+
{ volume }
69+
);
70+
return res.json({ message: 'Рейтинг успешно изменён' });
71+
}
72+
return res.json({ message: 'Рейтинг уже изменён' });
73+
} catch (error) {
74+
return res.status(400).json({
75+
error: error.toString(),
76+
});
77+
}
78+
},
79+
deleteRate: async (req, res) => {
80+
const { questionId } = req.params;
81+
const { commentId } = req.params;
82+
83+
try {
84+
const question = await Question.findById(questionId);
85+
const comment = await Comment.findById(commentId);
86+
87+
const checkRate = await Rate.findOne(
88+
commentId
89+
? { rateFrom: req.user.userId, ratedComment: commentId }
90+
: {
91+
rateFrom: req.user.userId,
92+
ratedQuestion: questionId,
93+
}
94+
);
95+
if (checkRate.volume !== 0) {
96+
if (!commentId) {
97+
await Question.findByIdAndUpdate(questionId, {
98+
questionRateCount: question.questionRateCount - checkRate.volume,
99+
});
100+
await Rate.findByIdAndUpdate(checkRate._id, { volume: 0 });
101+
return res.json({ message: 'Оценка удалена' });
102+
}
103+
await Comment.findByIdAndUpdate(commentId, {
104+
commentRateCount: comment.commentRateCount - checkRate.volume,
105+
});
106+
await Rate.findByIdAndUpdate(checkRate._id, { volume: 0 });
107+
return res.json({ message: 'Оценка удалена' });
108+
}
109+
return res.json({ message: 'Оценка уже удалена' });
110+
} catch (error) {
111+
return res.status(400).json({
112+
error: error.toString(),
113+
});
114+
}
115+
},
116+
};

src/controllers/users.controller.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ module.exports.usersController = {
111111
res.json(user.favorites);
112112
} catch (e) {
113113
res.status(400).json({
114-
message: `Ошибка при добавлении вопроса в избранные:${e.toString()}`,
114+
message: `Ошибка при удалении вопроса из избранных:${e.toString()}`,
115115
});
116116
}
117117
},

src/models/Comment.model.js

+4
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ const commentSchema = Schema(
1717
ref: 'Question',
1818
required: true,
1919
},
20+
commentRateCount: {
21+
type: Number,
22+
default: 0,
23+
},
2024
},
2125
{ timestamps: true }
2226
);

src/models/Question.model.js

+4-14
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,5 @@
11
const { Schema, model } = require('mongoose');
22

3-
const rateSchema = Schema(
4-
{
5-
user: {
6-
type: Schema.Types.ObjectId,
7-
},
8-
volume: {
9-
type: Number,
10-
enum: [-1, 1],
11-
},
12-
},
13-
{ timestamps: true }
14-
);
15-
163
const questionSchema = Schema(
174
{
185
question: {
@@ -32,7 +19,10 @@ const questionSchema = Schema(
3219
type: Number,
3320
default: 0,
3421
},
35-
rates: [rateSchema],
22+
questionRateCount: {
23+
type: Number,
24+
default: 0,
25+
},
3626
deleted: {
3727
type: Boolean,
3828
default: false,

0 commit comments

Comments
 (0)