LoopBack 远程方法和对模型数据的访问

LoopBack Remote Methods and Access to Model Data

我已经为此工作了几个小时,但我完全迷失了方向,因为环回文档没有帮助。

我正在尝试将应用程序逻辑写入模型。相关文档是 here。遗憾的是,该示例除了将外部值传递到远程方法并再次返回外,没有演示任何有用的东西。我想了解如何在此上下文中 运行 查询并访问模型数据,但我已经搜索了几个小时,甚至无法找到有关这些简单任务的文档。也许我只是在错误的地方寻找。有人可以帮忙吗?

通常,您可以通过所有模型获得的内置方法完成您想要做的大部分事情,例如查询和访问模型数据(CRUD 操作);参见 http://docs.strongloop.com/display/LB/Working+with+data。为这些定义远程方法(自定义 REST 端点)是多余的。

如果需要,您可以在远程方法代码中访问标准 model CRUD Node APIs(例如 myModel.create()、myModel.find()、myModel.updateAll())。

您还可以在 https://github.com/strongloop/loopback-example-app-logic

中找到更多相关示例

下面是一个使用入门应用 https://github.com/strongloop/loopback-getting-started 应用的示例。它定义了一个远程方法,该方法接受一个数字 arg 并将具有该 ID 的咖啡店名称打印到控制台:

这段代码在common/models/coffeeshop.js:

module.exports = function(CoffeeShop) {
...
  // Return Coffee Shop name given an ID.
  
  CoffeeShop.getName = function(shopId, cb) {
    CoffeeShop.findById( shopId, function (err, instance) {
        response = "Name of coffee shop is " + instance.name;
        cb(null, response);
        console.log(response);
    });
  }
...
  CoffeeShop.remoteMethod (
    'getName', 
    {
      http: {path: '/getname', verb: 'get'},
      accepts: {arg: 'id', type: 'number', http: { source: 'query' } },
      returns: {arg: 'name', type: 'string'}
     }
  );
};

您可以使用 API Explorer 加载 http://0.0.0.0:3000/explorer/#!/CoffeeShops/getName 然后输入一个数字(应用程序中最初只有三个咖啡店)作为查询参数并点击 "Try It Out!"

或者只是得到一个 URL 比如 http://0.0.0.0:3000/api/CoffeeShops/getid?id=1

兰特

我终于发现了我的问题。对象属性必须在调用 CRUD 操作的函数的回调中加载。以下语法对我有用:

module.exports = function (TestModel) {
    TestModel.testRemoteMethod = function (id, name, cb) {
        TestModel.findOne({where: {id: id}}, function(err, modelInstance) {
            //modelInstance has properties here and can be returned to
            //the API call using the callback, for example:
            cb(null, {"name": modelInstance.name});
        }
    }
    TestModel.remoteMethod('testRemoteMethod',
        //..rest of config