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

前端 未结 2 1790
挽巷
挽巷 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"}}
    

提交回复
热议问题