Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- router
- .route("/")
- .get(controller.eventStream)
- .post(controller.sendNotification);
- import axios from "axios";
- import eventEmitter from '../services';
- const controller = {
- eventStream: (req, res, next) => {
- console.log("Inside event stream");
- res.writeHead(200, {
- "Content-Type": "text/event-stream",
- "Cache-Control": "no-cache",
- "Connection": "keep-alive"
- });
- eventEmitter.on("sse", (event, data) => {
- console.log('Event Triggered');
- res.write(`event: ${event}ndata: ${JSON.stringify(data)} nn`);
- });
- req.on("close", () => {
- console.log("Inside Close");
- res.end();
- });
- },
- sendNotification: (req, res, next) => {
- try {
- const {
- userId,
- action,
- type,
- item_id,
- } = req.body;
- // First check the type of activity that has been performed
- switch (type) {
- case "topic":
- // Then check the type of action that has been done
- switch (action) {
- case "edit":
- console.log("Topic edited");
- const data= 'John Doe has edited a topic';
- eventEmitter.emit("sse", `edit-topic`, data);
- break;
- }
- break;
- }
- res.send('sse successfully send');
- } catch (error) {
- res.status(500).json({error: 'SSE failed'});
- }
- }
- };
- export default controller;
- export default new events.EventEmitter();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement