如何通过autosubscribe pub / sub捕获具有UPDATE的链接集合的事件?

时间:2015-02-18 19:59:01

标签: sails.js waterline

我疯狂地搜索了互联网,这些帖子似乎与我最想做的事情有关:

sails js cheatsheet

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

Filtering socket.io subscriptions

但他们没有太大帮助

我有 样板房

autosubscribe:['add:people','update:people']
attributes:{
     people:{collection:'people',via:'room'},
     temp:{type:'integer'}
},

模特儿

 attributes: {
      name:{type:'string'},
      room:{model:'rooms'},
      status:{type:'string',enum:['frustratedWithOfficialDocumentationBeingSoFracturedBetween:HiddenGitHubs_GoogleMisdirectsOnWebsite_OldYoutubes_ConceptsReferenceWhichAreForNoReasonSplitUp','personIsDead']
 },

现在,让我们说,不是在房间里添加另一个人(可能会触发publishAdd事件),我发现我的一个人已经死了,我只需要更新他们的状态

People.findOne({name:'mrHappy'}).exec(err,mrHappyObj){
    mrHappyObj.status = 'personIsDead'
    mrHappyObj.save()  //etc
    People.publishUpdate(mrHappyObj.id,{status:mrHappyObj.status})
})

所以这对于所有订阅'mrHappy'的人来说都很棒,但是如果我能找到能告诉他与之相关的房间的东西,那就太棒了,他会自动死,我不在乎它是不是它是什么只给我mrHappy的id,我真的想自动得到通知。

我试过但不必阅读的奖金。 我在我的People模型中编写了这个函数,但它看起来非常糟糕

afterUpdate: function(updatedRecord, next)
 {
 sails.log.debug("I updated a People! derp",updatedRecord);
 sails.log.debug("key is ",sails.models[this.identity].primaryKey);
        var pKey = sails.models[this.identity].primaryKey
 var thisModelId = this.identity
        _.each(Z.getAssociationParents(this.identity), function(association) {
    // //so we now have the name of a parent model, we now have to find the id() of the parent that this
    // //NEW thing is pointing to?
    // //This is the parent that needs to be notified that he now owns a new vehicle. We have to take 
    // //the socket in his room and then use it to subscribe to this change!
//                 console.log("parent model found:",association)
                sails.log.debug("parent room",'sails_model_'+association+'s_'+ updatedRecord[association]+':'+'update')
                var sockets = sails.sockets.subscribers('sails_model_'+association+'s_'+ updatedRecord[association]+':'+'update')


                sails.log.debug("child room",'sails_model_'+thisModelId+'_'+ updatedRecord[pKey] +':'+'update')
                var deleteMeSocketsInChild = sails.sockets.subscribers('sails_model_'+thisModelId+'_'+ updatedRecord[pKey] +':'+'update')

                sails.log.debug("sockets in parent:", sockets, "child:",deleteMeSocketsInChild)

                for(var s in sockets)
                {
                    var sock = sails.io.sockets.socket(sockets[s]);

 //TODO !! send the subscribe method the needed primary key object
                    sails.models[thisModelId].subscribe(sock, Z.subscribePluralizer(pKey,updatedRecord[pKey])); //TODO - get the primary key as the last paramater to this function (updaterd record
 sails.log.debug("break")
    //   //could pass it a null


    // //If i am correct, updatedRecord is the whole record that has been updated. We are wanting to 
    // //subscribe the parent socket(s) to it. If this doesn't work , try using the information within
    // //the udpatedRecord to do the subscribe unless you can think of a better way.
 sails.log.debug("sockets in parent:", sockets, " NEW child:",deleteMeSocketsInChild)
                }

        });
 next()
 }

其他功能

 //return the models that are your parents
 getAssociationParents: function(modelName) {
 var assocArr = []
 if (sails.models[modelName]) {
 for (var a in sails.models[modelName].attributes) {
 if (sails.models[modelName].attributes[a].model)
 assocArr.push(a)
 }
 }
 return assocArr
 },


 //inspired by the pluralize function in \sails\lib\hooks\pubsub\index.js - we have to wrap our primary key up all pretty for it
 // since we don't expect our updatedRecords function to return an array of new objects (it shouldn't) we won't use the _.map function from pluralize
 subscribePluralizer: function(pKey, value) {
 //this function should be examined before using - 1-28-2015
 var newObj = {}
 newObj[pKey] = value
 newObj = [newObj]


 return newObj
 },

1 个答案:

答案 0 :(得分:2)

我愿意接受这里的建议。但这是一种享受

你可以把它放在你的模型中(或者理想地将它打包成服务或其他东西)

  afterUpdate:function(updated,cb){
    var self = this
    Z.publishParentUpdate(updated,self, function(err){
        if(err){sails.log.debug(self.identity,'afterUpdate error',err)}
        try{
            sails.models[self.identity].publishUpdate(updated.id,updated)
            cb()
        }catch(err){sails.log.warn('error at end of afterupdate!',err)}
    })
  }

然后这些坏男孩在你的服务中,我使用Z.js作为我的

publishParentUpdate:function(updatedObj,theThis,cb){
        //iterate over all the attributes that have a model key in the attributes of this model
        var error = null
        _.each(Z.getAssociationParents(theThis.identity), function(association) {
            var parentModel = sails.models[theThis.attributes[association].model]  //we can use this to directly address the parent model and do its finds / updates
            var embeddedUpdateObj = {} //container for the object that we are going to fake the update message with
            embeddedUpdateObj[theThis.identity]=updatedObj //set the updated properties inside the model
            try{ //probably don't need to try catch, but since we could make a mistake assuming some things above it seems smarter
                parentModel.publishUpdate(updatedObj[association],embeddedUpdateObj) //updating based on the id contained in our model and then packing in our happy object
            }catch(err){
                sails.log.warn('error while doing a collection update',err)
                error = err
            }
            cb(error)
        });
    },

    getAssociations: function(modelName) { //modelName is string!
        //function returns
        var assocArr = []
        if (sails.models[modelName]) {
            for (var a in sails.models[modelName].attributes) {
                if (sails.models[modelName].attributes[a].collection)
                    assocArr.push(a)
            }
        }
        return assocArr
    },

    //return the models that are your parents
    getAssociationParents: function(modelName) {
        var assocArr = []
        if (sails.models[modelName]) {
            for (var a in sails.models[modelName].attributes) {
                if (sails.models[modelName].attributes[a].model)
                    assocArr.push(a)
            }
        }
        return assocArr
    },