如何在Loopback中添加模型的非远程方法?

时间:2016-03-11 21:38:14

标签: loopbackjs

如何将本地方法添加到Model 实例?换句话说,模型实例上的一个方法将由服务器执行,而不是通过其余接口公开。

我希望能够在服务器上执行的操作:

Person.findById(1, (err, person) => {
    let b = person.customFunction();
});

但我不希望customFunction暴露在其余界面上。

我知道你可以在这样的模型上创建一个远程方法:

module.exports = function(Person){

    Person.greet = function(msg, cb) {
      cb(null, 'Greetings... ' + msg);
    }

    Person.remoteMethod(
        'greet', 
        {
          accepts: {arg: 'msg', type: 'string'},
          returns: {arg: 'greeting', type: 'string'}
        }
    );
};

我知道如果你不再调用Person.remoteMethod(),你将为Model类本身添加一个仅服务器的方法,但这不是我想要的。

1 个答案:

答案 0 :(得分:0)

这很简单,您只需使用Javascript的原型功能。在Person.js中,只需添加:

Person.prototype.customFunction = function() {
   console.log('my custom code');
};

然后,提供person个实例,您可以致电:

person.customFunction();
相关问题