【问题标题】:Add nested remote method with loopbackjs使用 loopbackjs 添加嵌套的远程方法
【发布时间】:2017-12-10 04:38:15
【问题描述】:

我在工作中使用 strongloop 的 loopbackjs 来实现 API。

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

所以我可以这样做:

GET /cats/{:id}/meow

Cat 模型属于User 模型。

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

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

有人知道怎么做吗?

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

【问题讨论】:

    标签: loopbackjs


    【解决方案1】:

    可以在User Model中定义一个远程方法,然后用它来调用CatModel的喵方法

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

    【讨论】:

      【解决方案2】:

      使用nestRemoting('relationName')。它没有很好的文档记录,但是对于您的模型,您可以使用:

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

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

      【讨论】:

        【解决方案3】:

        我有一个解决方案需要与大家分享

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

        希望这个解决方案对你有帮助

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-17
          • 2015-05-29
          • 2020-06-01
          • 1970-01-01
          • 2022-07-26
          相关资源
          最近更新 更多