sails.js - 如何通过自动订阅发布/订阅来捕获具有更新的链接集合的事件?

标签 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”的每个人来说都很棒,但如果我能找到可以告诉 ROOM 他与之相关的东西他自动死了,那就太棒了,我不在乎它是什么只给我 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
 },

最佳答案

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

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

  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
    },

关于sails.js - 如何通过自动订阅发布/订阅来捕获具有更新的链接集合的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28592768/

相关文章:

javascript - sailsjs - waterline 是否可以智能方式支持 mongodb?

Javascript - Promises 和 forEach

javascript - 如何从 Sails JS Waterline 集合中获取指定字段的列表?

json - Sails js http post 请求,内容类型为 : application/json

javascript - SailsJS jQuery 在 View 中不起作用

javascript - Node : Waterline + Caolan/Async: bind function

mysql - Sailsjs MVC 将参数从外部 API 映射到多个模型

sails.js - 在一个模型中使用两个不同的适配器

javascript - npm 不安装下划线包

javascript - Sails 政策 - 通过协会搜索