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

Push notification for multiple users when add new item #9

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Fix push notification in post /items
  • Loading branch information
sharonm6 committed Apr 8, 2024
commit 69f96da428eecde08ddbee3d5eb7c30626b895fb
56 changes: 33 additions & 23 deletions routes/items.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
const express = require("express");
const sendEmail = require("../utils");
const fs = require("fs");
const webpush = require("web-push");
const path = require("path");
const middleware = require("../middleware");
// const notificationRouter = require("./notification");
const itemsRouter = express.Router();

const pool = require("../server/db");
Expand Down Expand Up @@ -55,37 +57,22 @@ itemsRouter.post("/", async (req, res) => {
[email]
);

// query to get keys of users subscribed for push notifications
const userNotifKeys = await pool.query(
`SELECT notification_key FROM ${leaderboardTable} WHERE email!=$1 AND subscription=True AND notification_key IS NOT NULL`,
[email]
);

res.json(item.rows[0]); // send the response immediately after adding the item
let contentString = "";

// async function sendPushNotification() {
// // filter out undefined keys
// const subscriptionKeys = subscribedUsers.rows
// .map((user) => user.notification_key)
// .filter((key) => key !== undefined);
// // send push notification
// await axios.post(
// `${process.env.REACT_APP_AWS_BACKEND_URL}/notification/keys`,
// {
// subscriptionKeys: subscriptionKeys,
// notificationTitle: "A nearby item was added.",
// notificationBody: `A new item, ${name}, was added to ZotnFound!`,
// },
// {
// headers: {
// Authorization: `Bearer ${token}`, // verify auth
// },
// }
// );
// }
// sendPushNotification();

// COMMENT OUT FOR TESTING PURPOSES
if (process.env.NODE_ENV === "production") {
// Send push and email notifications to all subscribed users

function sendDelayedEmail(index) {
if (index >= subscribedUsers.rows.length) return;

// send email notification
let email = subscribedUsers.rows[index].email;
contentString += `A new item, ${name}, is added to ZotnFound!`;

Expand All @@ -107,6 +94,29 @@ itemsRouter.post("/", async (req, res) => {
setTimeout(() => sendDelayedEmail(index + 1), 500); // recursive call to iterate through all user emails
}

function sendPushNotifications(
subscriptionKeys,
notificationTitle,
notificationBody
) {
console.log("Sending push notifications...");
const payload = JSON.stringify({
title: notificationTitle,
body: notificationBody,
});

subscriptionKeys.forEach((subscription) => {
webpush
.sendNotification(JSON.parse(subscription), payload)
.catch(console.log);
});
}

sendPushNotifications(
userNotifKeys.rows.map((row) => row.notification_key),
"A nearby item was added.",
`A new item, ${name}, was added to ZotnFound!`
);
sendDelayedEmail(0);
}
} catch (error) {
Expand Down
59 changes: 42 additions & 17 deletions routes/notification.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,27 +30,52 @@ notificationRouter.post("/", (req, res) => {
webpush.sendNotification(subscription, payload).catch(console.log);
});

// Send notifications to all subscribed users
notificationRouter.post("/keys", (req, res) => {
console.log("Pushing Notifications to All Subscribed Users");
// Get array of subscription keys, title, and body
const { subscriptionKeys, notificationTitle, notificationBody } = req.body;
res.status(201).json({});
const payload = JSON.stringify({
title: notificationTitle,
body: notificationBody,
});
console.log(subscriptionKeys);
subscriptionKeys.forEach((subscription) =>
webpush
.sendNotification(JSON.parse(subscription), payload)
.catch(console.log)
);
});
// function sendPushNotifications(
// subscriptionKeys,
// notificationTitle,
// notificationBody
// ) {
// console.log("Sending Push Notifications");
// const payload = JSON.stringify({
// title: notificationTitle,
// body: notificationBody,
// });
// console.log(subscriptionKeys);

// subscriptionKeys.forEach((subscription) =>
// webpush
// .sendNotification(JSON.parse(subscription), payload)
// .catch(console.log)
// );
// }

// // Send notifications to all subscribed users
// notificationRouter.post("/keys", (req, res) => {
// console.log("Pushing Notifications to All Subscribed Users");
// const { subscriptionKeys, notificationTitle, notificationBody } = req.body;
// res.status(201).json({});

// console.log("Sending Push Notifications");
// const payload = JSON.stringify({
// title: notificationTitle,
// body: notificationBody,
// });
// console.log(subscriptionKeys);

// subscriptionKeys.forEach((subscription) =>
// webpush
// .sendNotification(JSON.parse(subscription), payload)
// .catch(console.log)
// );
// });

notificationRouter.get("/test", (req, res) => {
console.log("Testing Routing!");
res.status(201).json({ message: "Routing is working!" });
});

module.exports = notificationRouter;
// module.exports = {
// router: notificationRouter,
// sendPushNotifications: sendPushNotifications,
// };