Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

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

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...