How to get added record (not just the id) through publishAdd()-notification?

前端 未结 2 1763
挽巷
挽巷 2021-01-15 10:05

Each Sails.js model has the method publishAdd(). This notifies every listener, when a new record was added to a associated model.

This notification does

相关标签:
2条回答
  • 2021-01-15 10:07

    I know this is old, but I just had to solve this again, and didn't like the idea of dropping in duplicate code so if someone is looking for alternative, the trick is to update the model of the newly created record with an afterCreate: method.

    Say you have a Game that you want to your Players to subscribe to. Games have notifications, a collection of text alerts that you only want players in the game to receive. To do this, subscribe to Game on the client by requesting it. Here I'm getting a particular game by calling game/gameId, then building my page based on what notifications and players are already on the model:

    io.socket.get('/game/'+gameId, function(resData, jwres) {
        let players = resData.players;
        let notifications = resData.notifications;
        $.each(players, function (k,v) {
            if(v.id!=playerId){
                addPartyMember(v);
            }
        });
        $.each(notifications, function (k,v) {
            addNotification(v.text);
        });
    });
    

    Subscribed to game will only give the id's, as we know, but when I add a notification, I have both the Game Id and the notification record, so I can add the following to the Notification model:

    afterCreate: function (newlyCreatedRecord, cb) {
        Game.publishAdd(newlyCreatedRecord.game,'notifications',newlyCreatedRecord);
    cb();}
    

    Since my original socket.get subscribes to a particular game, I can publish only to those subscriber by using Game.publishAdd(). Now back on the client side, listen for the data coming back:

    io.socket.on('game', function (event) { 
    if (event.attribute == 'notifications') {
        addNotification(event.added.text);
        }
    });
    

    The incoming records will look something like this:

     {"id":"59fdd1439aee4e031e61f91f",
     "verb":"addedTo",
    "attribute" :"notifications",
     "addedId":"59fef31ba264a60e2a88e5c1",
     "added":{"game":"59fdd1439aee4e031e61f91f",
     "text":"some messages",
     "createdAt":"2017-11-05T11:16:43.488Z",
     "updatedAt":"2017-11-05T11:16:43.488Z",
     "id":"59fef31ba264a60e2a88e5c1"}}
    
    0 讨论(0)
  • 2021-01-15 10:11

    There's no way to get this record using the default publishAdd method. However, you can override that method and do the child record lookup in your implementation.

    You can override publishAdd on a per-model basis by adding a publishAdd method to that model class, or override it for all models by adding the method to the config/models.js file.

    I would start by copying the default publishAdd() method and then tweaking as necessary.

    0 讨论(0)
提交回复
热议问题