Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
394 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...