使用loopbackjs添加嵌套的远程方法

时间:2015-12-08 17:20:11

标签: loopbackjs

我正在使用strongloop的loopbackjs来实现API。

对于模型Cat我定义了一个远程方法,我们称之为meow

所以我能做到:

GET /cats/{:id}/meow

Cat模型属于User模型。

现在我希望能够做到这样的事情:

GET /users/{:id}/cats/{:id}/meow

有谁知道怎么做?

我已经尝试过nestRemoting,它只适用于嵌套的“蓝图”方法。

3 个答案:

答案 0 :(得分:2)

您可以在用户模型中定义远程方法,然后使用它来调用CatModel的meow方法

UserModel.someRemoteMethod = function(id1,id2,cb){
     CatModel.meow(id2,cb);
 }


  UserModel.remoteMethod(
    'someRemoteMethod',
    {
      accepts: [
        {arg: 'id1', type: 'number', required: true},
        {arg: 'id2', type: 'number', required: true}
      ],
      http: {path: '/:id1/cats/:id2/meow', verb: 'get'}
    }
  );

答案 1 :(得分:0)

使用nestRemoting('relationName')。它没有详细记录,但对于您的模型,您可以使用:

User.on('attached', function() {
   User.nestRemoting('catRelation');
}

将它放在user.js文件中,你应该得到你想要的终点。

答案 2 :(得分:0)

我得到了一个我需要与大家分享的解决方案

nestRemoting函数取一个选项json对象,其中包含一个名为filterMethod的属性,此方法过滤模型函数只获取默认方法,所以我在(else if)中通过自定义函数传递了此属性回调函数来检查我的远程方法(DoWhat) )并将其归还

server.models.Client.nestRemoting('units', {filterMethod: function(method, relation) {
        let regExp = /^__([^_]+)__([^_]+)$/;
        let matches = method.name.match(regExp);
        if (matches) {
            return '__' + matches[1] + '__' + relation.name + '__' + matches[2];
        } else if (method.name === 'DoWhat') {
            return method.name;
        }
    }});

我希望这个解决方案可以帮助你