Conditional publish events

后端 未结 1 485
粉色の甜心
粉色の甜心 2021-01-21 02:25

Introduction

I\'m building a private messaging system using sails, but this question can apply to pretty much anything. I\'ll be using the messaging system as an examp

相关标签:
1条回答
  • 2021-01-21 02:32

    You have a few options here, but all of them involve not really using the default publishCreate method, which will just blast out the created message to everyone who was subscribed to it via .watch().

    The first option is to use associations to link your Message model to the users who should know about it, and then listen for the publishAdd message instead of publishCreate. For example, if there's an association between a Message instance and the User instances who represent the sender and recipient, then the default publishCreate logic will also trigger a publishAdd for the related users, indicating that a new Message has been added to their messages (or whatever you name it) collection.

    The second option is to override the default publishCreate for Message, to have it send only to the correct users. For example, if only the recipient should be notified, then in api/models/Message.js you could do:

    attributes: {...},
    publishCreate: function (values, req, options) {
        User.publish(values.recipient, {
            verb: "created",
            data: values, 
            id: values.id
        }, req);
    }
    

    As a slight alternative, you can place your custom code in the model's afterPublishCreate method instead, which the default publishCreate will then call. This has the benefit of maintaining the default code that handles calling publishAdd for associated models; the trick would be just to make sure that no one was subscribed to the model classroom via .watch(), so that the default publishCreate doesn't send out created messages to users who shouldn't see them.

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