环回:如何将模型的afterRemote添加到另一个模型 [英] Loopback: How to add afterRemote of a model to another model

查看:132
本文介绍了环回:如何将模型的afterRemote添加到另一个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的通知模型

I have Notification model which looks like this

"use strict";

module.exports = function(Notification) {


};

还有另一个模型是Post:

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" }
  });
}

我想要的是在通知模型内部添加Post的afterRemote方法?

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

是否可以进行环回?

它看起来应该像:

"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');
  });
};

但这不起作用.

注意::我可以自己完成发布模型,但我想在Notification模型中添加所有通知逻辑,以简化和将来进行自定义.

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.

推荐答案

您可以使用事件来完成.

You can use events to do.

环回应用程序在加载所有启动脚本后启动时,会发出started事件

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

Notification模型中的操作如下:

  "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');
       });
     });
    };

或创建启动脚本并发出自定义事件,例如"allModelsLoaded".因此,请确保引导脚本是最后一个要运行的脚本.引导脚本默认情况下按字母顺序运行.因此,使z.js并在其中发出该自定义事件,然后在Notification模型中侦听该事件.

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.

这篇关于环回:如何将模型的afterRemote添加到另一个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆