Loopback: How to add afterRemote of a model to another model

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 19:24:34

问题


I have Notification model which looks like this

"use strict";

module.exports = function(Notification) {


};

And I have another model which is Post:

"use strict";

module.exports = function(Post) {
   Post.prototype.postLike = function(options, cb) {
          this.likes.add(options.accessToken.userId);

          cb(null, "sucess");
   };

   Post.remoteMethod("postLike", {
    isStatic: false,
    accepts: [{ arg: "options", type: "object", http: "optionsFromRequest" }],
    returns: { arg: "name", type: "string" },
    http: { path: "/like", verb: "post" }
  });
}

What I want is to add afterRemote method of Post inside of notification model ?

Is it possible in loopback ?

It should looks like :

"use strict";

module.exports = function(Notification) {

  var app = require("../../server/server.js");
  var post = app.models.Post;

  post.afterRemote('prototype.postLike', function(context, like, next) {
    console.log('Notification after save for Like comment');
  });
};

But this does not work.

NOTE: I can do it Post model itself, but I want to add all of my notification logic in Notification model for simplification and future customization.


回答1:


You can use events to do.

Loopback application emits started event when it started after all boot scripts loaded here

and in Notification model do like this :

  "use strict";

    module.exports = function(Notification) {

      var app = require("../../server/server.js");

      app.on('started', function(){
      var post = app.models.Post;
      post.afterRemote('prototype.postLike', function(context, like, next) {
        console.log('Notification after save for Like comment');
       });
     });
    };

Or create a boot script and emit a custom event like 'allModelsLoaded'. So make sure the boot script is the last one to be run. Boot scripts run in alphabetic order by default. So make z.js and emit that custom event there then listen to that event in Notification model.




回答2:


Loopback boot process first loads models, and then invoke boot scripts once all models have been loaded. If your aim is to consolidate things across models, then it is better to do this in a boot script, rather than in model.js file.



来源:https://stackoverflow.com/questions/45586708/loopback-how-to-add-afterremote-of-a-model-to-another-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!