Skip to content

Commit

Permalink
netlify function
Browse files Browse the repository at this point in the history
  • Loading branch information
emilyliublair committed Nov 17, 2024
1 parent f2c83b2 commit 7ff66db
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 198 deletions.
128 changes: 0 additions & 128 deletions netlify/functions/hello.mts

This file was deleted.

124 changes: 54 additions & 70 deletions netlify/functions/notif.mts
Original file line number Diff line number Diff line change
@@ -1,56 +1,50 @@
import { Handler, Config } from '@netlify/functions';
import juno from 'juno-sdk';
import NotificationModel from '../../src/server/db/models/NotificationModel';
import dbConnect from '../../src/server/db/dbConnect';
// import CommentModel from '../../src/server/db/models/CommentModel';
// import PostModel from '../../src/server/db/models/PostModel';
// import UserModel from '../../src/server/db/models/UserModel';
// import { deleteNotification } from '../../src/server/db/actions/NotificationActions';
// import { PopulatedComment } from '../../src/utils/types/comment';

// async function generateEmailContents(commentIds: string[]) {
// const postsToComments: { [postId: string]: PopulatedComment[] } = {};
// let content = "";

// const comments = await CommentModel.find({ _id: { $in: commentIds } }).populate('author');

// for (const comment of comments) {
// const postId = comment.post._id.toString();
// if (!postsToComments[postId]) {
// postsToComments[postId] = [];
// }
// postsToComments[postId].push(comment);
// }

// for (const postId in postsToComments) {
// const post = await PostModel.findById(postId); // Fetch the post title
// if (post) {
// content += `<strong>${post.title}</strong><br>`;
// const postComments = postsToComments[postId];

// for (const comment of postComments) {
// content += `${comment.author?.lastName} family commented: ${comment.content}<br>`;
// }

// content += "<br><br>";
// }
// }

// return {
// type: "text/html",
// value: content,
// };
// }
// netlify/functions/hello.mts
import { Handler } from '@netlify/functions';
import { Config } from '@netlify/functions';
import juno from "juno-sdk";
import NotificationModel from "../../src/server/db/models/NotificationModel";
import dbConnect from "../../src/server/db/dbConnect";
import CommentModel from "../../src/server/db/models/CommentModel";
import PostModel from "../../src/server/db/models/PostModel";
import UserModel from "../../src/server/db/models/UserModel";
import { deleteNotification } from "../../src/server/db/actions/NotificationActions";
import { PopulatedComment } from "../../src/utils/types/comment";

async function generateEmailContents(commentIds: string[]) {
const postsToComments: { [postId: string]: PopulatedComment[] } = {};
let content = "";
const comments = await CommentModel.find({ _id: { $in: commentIds } }).populate('author');
for (const comment of comments) {
const postId = comment.post._id.toString();
if (!postsToComments[postId]) {
postsToComments[postId] = [];
}
postsToComments[postId].push(comment);
}
for (const postId in postsToComments) {
const post = await PostModel.findById(postId); // Fetch the post title
if (post) {
content += `<strong>${post.title}</strong><br>`;
const postComments = postsToComments[postId];
for (const comment of postComments) {
content += `${comment.author?.lastName} family commented: ${comment.content}<br>`;
}
content += "<br><br>";
}
}
return {
type: "text/html",
value: content,
};
}

const handler: Handler = async(event, context) => {
const handler: Handler = async (event, context) => {
try {
console.log('juno init')
juno.init({
apiKey: process.env.JUNO_API_KEY as string,
baseURL: "https://api-gateway.whitesmoke-cea9a269.eastus.azurecontainerapps.io"
})
});

// Fetch notifications and group by user
await dbConnect();
const notifications = await NotificationModel.find({});
const usersToNotify: { [userId: string]: string[] } = {};
Expand All @@ -65,8 +59,6 @@ const handler: Handler = async(event, context) => {

for (const userId in usersToNotify) {
const user = await UserModel.findById(userId);

// user has opted out of notifications, delete currently stored
if (!user || !user.email || !user.notificationPreference) {
for (const commentId of usersToNotify[userId]) {
try {
Expand All @@ -77,12 +69,11 @@ const handler: Handler = async(event, context) => {
}
} else {
const emailContents = await generateEmailContents(usersToNotify[userId]);

const response = await juno.email.sendEmail({
recipients: [
{
email: "[email protected]",
name: `${user.lastName} Family`,
email: `{user.email}`,
name: `{user.lastName} Family`,
},
],
bcc: [],
Expand All @@ -91,7 +82,7 @@ const handler: Handler = async(event, context) => {
email: process.env.JUNO_SENDER_EMAIL as string,
name: process.env.JUNO_SENDER_NAME as string,
},
subject: "FOCUS Community Updates",
subject: "FOCUS Community Updates", // TODO: update
contents: [emailContents],
});

Expand All @@ -105,28 +96,21 @@ const handler: Handler = async(event, context) => {
}
}
}
console.log(notifications)

const response = {
message: "hello",
eventDetails: event
}

return {
statusCode: 200,
body: JSON.stringify(response),
}
statusCode: 200,
body: JSON.stringify({ message: "Successfully sent email" }),
};
} catch (error) {
console.error('Error sending notifications:', error);
console.error("Error occurred:", error);
return {
statusCode: 500,
body: JSON.stringify({error: "Error sending notifications"})
}
body: JSON.stringify({ error: "Internal Server Error" }),
};
}
}

export const config: Config = {
schedule: '00 18 * * *', // 12:45 PM EST (5:45 PM UTC)
};
export { handler };

export default handler;
export const config: Config = {
schedule: "0 17 * * *" // schedule function to run at 5pm UTC every day
}

0 comments on commit 7ff66db

Please sign in to comment.