All files / src/routes/root_routes notifications_get.js

100% Statements 13/13
100% Branches 2/2
100% Functions 6/6
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34        77x   77x 2x 2x           2x           2x 2x   2x 2x 2x     2x 2x        
import SystemController from "../../controllers/system-controller/SystemController.js";
import asyncRouteHandler from "../../utilities/asyncRouteHandler.js";
import eventEmiter from "../../utilities/eventEmiter.js";
 
let notificationsReceivers = [];
 
eventEmiter.on("notification", (notification) => {
    notificationsReceivers.forEach((receiver) => {
        receiver(notification)
    })
})
 
export default asyncRouteHandler(
    async function notifications_get(req, res) {
        res.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive'
        });
 
        const notifications = await SystemController.getNotifications(req.adminId);
        notifications?.length && res.write(`data: ${JSON.stringify(notifications)}\n\n`);
 
        const receiverIndex = notificationsReceivers.length
        notificationsReceivers.push((notification) => {
            res.write(`data: ${JSON.stringify(notification)}\n\n`)
        })
 
        res.on("close", () => {
            notificationsReceivers = notificationsReceivers.filter((_, index) => index !== receiverIndex)
        })
    }
)