Sails.js: subscribing a user to certain actions in a request

In my Sails project, I have a User model / controller and a Request model / controller, as well as a Dashboard controller. The user can request data using RequestController.create , and the administrator can approve it using RequestController.grant .

I want to do this to notify the user when one of his / her requests is approved (updated). In RequestController.grant I call Request.publishUpdate(...) , and in my DashboardController.display I call

 Request.find(req.session.user.id, function(err, requests) { ... Request.subscribe(req, requests, ['update']) ... }); 

Then, in the /dashboard/display view, I put the <script> tags:

 <script> // Socket handling for notifications io.socket.on("request", function(obj) { alert(obj.verb); alert(obj.data); alert(obj.previous); }); </script> 

However, after approving the user request and switching to the control panel, an alert does not appear. The script for sails.io is already loaded, without errors in the console. Am I doing something wrong?

0
source share
1 answer

The likely problem is that you are using Request.subscribe in an HTTP call. I assume this is because it seems that you are using DashboardController.display to display the view. In this case, Request.subscribe does nothing at all (it should really display a warning) because it cannot know which socket is signing!

If you want to keep the logic of the controller the same (you can use the requests array as a local view to load some data on the page), that's fine; a quick refactor should check if its socket in action calls:

 // Also note the criteria for the `find` query below--just sending an // ID won't work for .find()! Request.find({user: req.session.user.id}, function(err, requests) { ... // If it a socket request, subscribe and return success if (req.isSocket) { Request.subscribe(req, requests, ['update']) return res.send(200); } // Otherwise continue on displaying the view else { ... return res.view('dashboard', {requests: requests}); } }); 

Then, somewhere in your view, call io.socket.get('/dashboard/display') to subscribe to request instances.

You can also use drawings to subscribe to requests from the front, doing something like io.socket.get('/request?user='+userId) if you put the user ID in local residents and add it somewhere in your viewing template, for example. <script>var userId=<%=user.id%></script> .

+1
source

Source: https://habr.com/ru/post/973622/


All Articles