Skip to content
24 changes: 24 additions & 0 deletions models/Notification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import mongoose from 'mongoose';
const { Schema } = mongoose;

const notificationSchema = new Schema({
labId: { type: String, required: true },
type: { type: String, required: true },
resourceId: { type: String, required: true },
recipients: [
{
role: {
type: [String],
enum: ["PI", "LAB_MANAGER", "RESEARCHER"],
required: true
},
type: [String],
}
],
createdAt: { type: Date, required: true, default: Date.now }
});

const Notification = mongoose.models.Notification ||
mongoose.model('Notification', notificationSchema);

export default Notification;
4 changes: 4 additions & 0 deletions services/notifications/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { startNotificationWatcher } from "./watchUpdates";

// Entry point for notification service
startNotificationWatcher();
38 changes: 38 additions & 0 deletions services/notifications/watchUpdates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import mongoose from "mongoose";
import { connectToDatabase } from "@/lib/mongoose";
import Notification from "@/models/Notification";

/**
* Starts a Change Stream watcher on the "products" collection.
* Inserts a DB_UPDATE notification whenever a product is updated.
*/
export async function startNotificationWatcher() {
await connectToDatabase();

const collection = mongoose.connection.collection("items");

const changeStream = collection.watch([], {
fullDocument: "updateLookup",
});

for await (const change of changeStream) {
if (change.operationType !== "update") continue;

// Get the updated document from the change stream
const updatedDoc = change.fullDocument;

// If there’s no document, skip this iteration
if (!updatedDoc) continue;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can add a comment here where we can check the quantity and compare it to the specified threshold. If it is less we continue else we will send a noti

// TODO: Check the quantity in updatedDoc
// If quantity is below the threshold, continue
// Otherwise, send a notification
await Notification.create({
_id: `notif_${Date.now()}`,
type: "DB_UPDATE",
labId: updatedDoc.labId ?? "unknown",
resourceId: String(updatedDoc._id),
recipients: [],
});
}
}