Skip to content

Commit 0ec9176

Browse files
Merge pull request #1 from amitmalakariitb/notification
Added notification model and controller
2 parents e6f3eef + 5c0a1b2 commit 0ec9176

File tree

8 files changed

+656
-341
lines changed

8 files changed

+656
-341
lines changed

api/controllers/infopostControllers.js

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@ const dotenv = require("dotenv");
33
dotenv.config();
44
const infopostModel = require("../models/infopostModel");
55
const imageModel = require("../models/imageModel");
6+
const userModel = require("../models/userModel");
7+
const notificationController = require("../controllers/notificationController");
68
const path = require("path");
9+
710
// multer middleware for handling uploading images
811
const multer = require("multer");
12+
const ROLES_LIST = require("../../config/roles_list");
913
const storage = multer.diskStorage({
1014
destination: function (req, file, cb) {
1115
cb(null, "../html/uploads");
@@ -49,13 +53,18 @@ const postinfopost = asyncHandler(async (req, res) => {
4953
url: req.body.urls,
5054
images: savedImages,
5155
});
56+
const savedInfopost = await infopost.save();
57+
// Notify all students about the new infopost
58+
const allStudents = await userModel.find({ role: ROLES_LIST.STUDENT });
59+
const studentIds = allStudents.map(student => student._id);
60+
await notificationController.createNotification(1, studentIds, savedInfopost._id, "New infopost");
61+
62+
5263
const message = "Infopost posted successfully";
53-
await infopost.save().then((data) => {
54-
res.json({data,message});
55-
});
64+
res.json({ data: savedInfopost, message });
5665
});
5766
} catch (err) {
58-
res.status(400).res.json({ message: " An error occured while posting the infopost" });
67+
res.status(400).json({ message: "An error occurred while posting the infopost" });
5968
}
6069
});
6170

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
const asyncHandler = require("express-async-handler");
2+
const dotenv = require("dotenv");
3+
dotenv.config();
4+
const notificationModel = require("../models/notificationModel");
5+
const User = require('../models/userModel');
6+
const path = require("path");
7+
const ROLES_LIST = require("../../config/roles_list");
8+
9+
//Function for creating notifications
10+
const createNotification = asyncHandler(async (senderid, recipientlist, contentid, content) => {
11+
try {
12+
const newNotification = new notificationModel({
13+
senderid: senderid,
14+
recipientlist: recipientlist,
15+
contentid: contentid,
16+
content: content
17+
});
18+
await newNotification.save();
19+
console.log("Notification created:", newNotification);
20+
21+
22+
return newNotification;
23+
} catch (err) {
24+
throw new Error("An error occurred while creating notification"+err.message);
25+
}
26+
});
27+
28+
29+
// Function to get all notifications of a particular student
30+
const getNotificationsByStudent = async (req, res) => {
31+
try {
32+
const studentId = req.params.studentId;
33+
34+
const notifications = await notificationModel.find({ recipientlist: studentId });
35+
36+
res.json({ notifications });
37+
} catch (error) {
38+
console.error("Error retrieving notifications:", error);
39+
res.status(500).json({ error: 'An error occurred while retrieving notifications' });
40+
}
41+
};
42+
43+
module.exports = {
44+
createNotification,
45+
getNotificationsByStudent
46+
};

api/controllers/questionController.js

Lines changed: 68 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ const upload = multer({
4242
const questionModel = require("../models/questionModel");
4343
const userModel = require("../models/userModel");
4444
const imageModel = require("../models/imageModel");
45+
//import the controllers
46+
const notificationController = require("../controllers/notificationController");
4547

4648
//-------------------------------------------------------------------------------------------------------------------------------------
4749

@@ -302,43 +304,56 @@ const answerQ = asyncHandler(async (req, res) => {
302304

303305
const body = req.body["answers"];
304306
console.log("body", body);
305-
const um = await userModel.findOne({ user_ID: body.user_ID });
306-
if(!um){
307-
res.status(401).json({error:"User not found"})
307+
const um = await userModel.findOne({ user_ID: req.body.user_ID });
308+
if (!um) {
309+
return res.status(401).json({ error: "User not found" });
308310
}
309311
console.log("user model", um);
310312
let verified = false;
311313
if (um.role === 5980) {
312314
verified = true;
313315
}
314316
const message = "Successfully answered the question";
317+
// Update the question with the provided answer
315318
await questionModel
316-
.updateOne(
317-
{ _id: req.params.qid }, // this line is to find the question with the id
319+
.findByIdAndUpdate(
320+
req.params.qid,
318321
{
319322
$push: {
320-
answers: [
321-
{
322-
body: body.body,
323-
user_ID: body.user_ID,
324-
user_Name: um.name,
325-
images: savedImages,
326-
verified: verified,
327-
},
328-
],
323+
answers: {
324+
body: req.body.body,
325+
user_ID: req.body.user_ID,
326+
user_Name: um.name,
327+
images: savedImages,
328+
verified: verified,
329+
},
329330
},
330331
$set: { status: true },
331-
}
332+
},
333+
{ new: true } // To return the updated document
332334
)
333-
.then((data) => {
334-
res.json({data,message});
335+
.then(async (updatedQuestion) => {
336+
// To check if the question was found and updated
337+
if (!updatedQuestion) {
338+
return res.status(404).json({ error: "Question not found" });
339+
}
340+
// Notify the student that their question has been answered
341+
const studentId = updatedQuestion.user_ID;
342+
const answererId = req.body.user_ID;
343+
const notifMessage = "Your question has been answered";
344+
notificationController.createNotification(
345+
answererId,
346+
[studentId],
347+
req.params.qid,
348+
notifMessage
349+
);
350+
res.json({ data: updatedQuestion, message });
335351
});
336352
});
337353
} catch (err) {
338-
res.status(400).json({ message: "Error occured while answering the question" });
354+
res.status(400).json({ message: "Error occurred while answering the question" });
339355
}
340356
});
341-
342357
//Commenting
343358
//Commenting on a question
344359
//no point of keeping track of comments
@@ -347,42 +362,46 @@ const commentQ = asyncHandler(async (req, res) => {
347362
try {
348363
const cID = new mongoose.Types.ObjectId();
349364
const body = req.body["comments"];
350-
const um = await userModel.findOne({ user_ID: body.user_ID });
351-
if(!um){
352-
res.status(401).json({error:"User not found"})
365+
const um = await userModel.findOne({ user_ID: req.body.user_ID });
366+
if (!um) {
367+
return res.status(401).json({ error: "User not found" });
353368
}
354369
console.log("user model", um);
355370
const message = "Successfully commented on the question";
356-
await questionModel
357-
.updateOne(
358-
{ _id: req.params.qid },
359-
{
360-
$push: {
361-
comments: [
362-
{
363-
_id: cID,
364-
body: body.body,
365-
user_ID: body.user_ID,
366-
user_Name: um.name,
367-
},
368-
],
371+
// Update the question document by pushing the new comment
372+
await questionModel.findByIdAndUpdate(
373+
req.params.qid,
374+
{
375+
$push: {
376+
comments: {
377+
_id: cID,
378+
body: req.body.body,
379+
user_ID: req.body.user_ID,
380+
user_Name: um ? um.name : 'Unknown', // Handle case where user is not found
369381
},
370-
}
371-
)
372-
.then(async (data) => {
373-
console.log(cID.valueOf());
374-
//inserting posted comment id to user model
375-
376-
const temp = um.question_comments.concat([
377-
{ questionID: req.params.qid, commentID: cID.valueOf() },
378-
]);
379-
um.question_comments = temp;
380-
await um.save();
381-
res.json({data,message});
382-
});
382+
},
383+
},
384+
);
385+
//Notify the student that someone commented on their question
386+
const studentid = (await questionModel.findById(req.params.qid)).user_ID;
387+
const senderid = req.body.user_ID;
388+
const notifMessage = "Your question has been commented on";
389+
notificationController.createNotification(
390+
senderid,
391+
[studentid],
392+
req.params.qid,
393+
notifMessage
394+
);
395+
// Insert the posted comment ID to user model
396+
const temp = um.question_comments.concat([
397+
{ questionID: req.params.qid, commentID: cID.valueOf() },
398+
]);
399+
um.question_comments = temp;
400+
await um.save();
401+
res.json({ message });
383402
} catch (err) {
384403
console.log(err);
385-
res.status(400).res.json({ message: "Error occured while commenting on the question" });
404+
res.status(400).json({ message: "Error occurred while commenting on the question" });
386405
}
387406
});
388407

api/models/notificationModel.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const mongoose=require('mongoose')
2+
3+
const notificationSchema = mongoose.Schema({
4+
id: mongoose.Schema.Types.ObjectId,
5+
recipientlist: [{type: String, required: true}],
6+
senderid: {type: String, required: true},
7+
contentid: {type: String, required: true},
8+
content: {type: String },
9+
sent_At: {type: Date, default: Date.now},
10+
isseen: {type: Boolean, default: false, required: true}
11+
12+
});
13+
14+
const notificationModel = mongoose.model("notificationModel", notificationSchema);
15+
16+
module.exports = notificationModel;

api/routes/notificationRouters.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
const express = require('express');
2+
const router = express.Router();
3+
const notificationController = require('../controllers/notificationController');
4+
5+
// Route to get all notifications of a particular student
6+
router.get('/:studentId', notificationController.getNotificationsByStudent);
7+
8+
9+
module.exports = router;

0 commit comments

Comments
 (0)