Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. router
  2. .route("/")
  3. .get(controller.eventStream)
  4. .post(controller.sendNotification);
  5.  
  6. import axios from "axios";
  7. import eventEmitter from '../services';
  8.  
  9. const controller = {
  10. eventStream: (req, res, next) => {
  11. console.log("Inside event stream");
  12. res.writeHead(200, {
  13. "Content-Type": "text/event-stream",
  14. "Cache-Control": "no-cache",
  15. "Connection": "keep-alive"
  16. });
  17.  
  18. eventEmitter.on("sse", (event, data) => {
  19. console.log('Event Triggered');
  20. res.write(`event: ${event}ndata: ${JSON.stringify(data)} nn`);
  21. });
  22.  
  23. req.on("close", () => {
  24. console.log("Inside Close");
  25. res.end();
  26. });
  27. },
  28.  
  29. sendNotification: (req, res, next) => {
  30. try {
  31. const {
  32. userId,
  33. action,
  34. type,
  35. item_id,
  36. } = req.body;
  37.  
  38. // First check the type of activity that has been performed
  39. switch (type) {
  40. case "topic":
  41. // Then check the type of action that has been done
  42. switch (action) {
  43. case "edit":
  44. console.log("Topic edited");
  45. const data= 'John Doe has edited a topic';
  46. eventEmitter.emit("sse", `edit-topic`, data);
  47. break;
  48. }
  49. break;
  50. }
  51. res.send('sse successfully send');
  52. } catch (error) {
  53. res.status(500).json({error: 'SSE failed'});
  54. }
  55. }
  56. };
  57.  
  58. export default controller;
  59.  
  60. export default new events.EventEmitter();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement