powr-sdk-api
Version:
Shared API core library for PowrStack projects. Zero dependencies - works with Express, Next.js API routes, and other frameworks. All features are optional and install only what you need.
93 lines (88 loc) • 2.69 kB
JavaScript
;
const express = require('express');
const router = express.Router();
const {
getDb
} = require('../services/mongo');
// const tokenService = require('../services/tokenService');
// Get notifications
router.get('/', async (req, res) => {
const projectId = req.projectId;
try {
const query = {
projectId
};
console.log("Filter.....:", query);
const db = await getDb();
const notificationData = await db.collection('notifications').find(query).toArray();
if (!notificationData || notificationData.length === 0) {
console.log("Data not found.");
return res.status(200).json({
success: true,
notification: []
});
}
const sortedData = notificationData.sort((a, b) => new Date(b === null || b === void 0 ? void 0 : b.createdAt) - new Date(a === null || a === void 0 ? void 0 : a.createdAt));
console.log("Notifications retrieved and sorted:", sortedData);
return res.status(200).json({
success: true,
notification: sortedData
});
} catch (error) {
console.error("Error retrieving notifications:", error);
return res.status(500).json({
success: false,
message: "Failed to retrieve notifications."
});
}
});
// Send notification
router.post('/', async (req, res) => {
const {
title,
description,
filter,
imgurl
} = req.body;
const projectId = req.projectId;
if (typeof filter !== 'object' || Array.isArray(filter) || filter === null) {
return res.status(400).json({
success: false,
message: "Filter should be a valid object."
});
}
const notificationData = {
projectId,
filter,
imgurl,
title,
description,
createdAt: new Date()
};
try {
const db = await getDb();
const result = await db.collection('notifications').insertOne(notificationData);
if (result && result.insertedId) {
console.log("Notification added with ID:", result.insertedId);
// await tokenService.sendNotificationsToProjectUsers(projectId, notificationData);
return res.status(200).json({
success: true,
message: "Notification added and sent successfully.",
notificationId: result.insertedId
});
} else {
console.error("Insert operation failed. Result:", result);
return res.status(500).json({
success: false,
message: "Notification could not be added."
});
}
} catch (error) {
console.error("Error adding notification:", error);
return res.status(500).json({
success: false,
message: "Failed to add notification due to a server error."
});
}
});
module.exports = router;