Loopback.js如何使用Connector-rest?

时间:2018-10-10 03:39:42

标签: loopbackjs

我正在尝试使用带有连接器支架的示例应用程序。

https://github.com/strongloop/loopback-connector-rest

我的目标是制作以下api。

$ curl http://localhost:3001/addresses/17F54d4S9aLpvUEsk7MkYWafmzxJhhb9wW/balance
{
  "balance": 42030
}

余额是从blockchain.info api中检索的。

$ curl https://blockchain.info/balance?active=17F54d4S9aLpvUEsk7MkYWafmzxJhhb9wW
{"17F54d4S9aLpvUEsk7MkYWafmzxJhhb9wW": {
    "final_balance": 42030,
    "n_tx": 2,
    "total_received": 42030
}}

以下是我所做的。

  1. 创建环回应用
  2. 创建Rest数据源
  3. 创建地址模型

但是我不知道下一步该怎么做?我想我需要配置一些请求。我应该将其添加到datasources.json吗?如何从addresss.js调用它?

我的代码保存在github上。 https://github.com/y-zono/loopback-connector-rest-example


更新1

我找到了这个例子。

https://github.com/strongloop-community/loopback-example-connector/tree/rest

然后,我可以从blockchain.info获取数据。

https://github.com/y-zono/loopback-connector-rest-example/commit/f5e8f96a666f4fdab5d554e657f630635237c2c1

仍然不确定这是否是正常方法。我正在检查。

1 个答案:

答案 0 :(得分:1)

我找到了它,并确认Promise和async / await正常工作。

如果您有其他更好的方法,欢迎提出任何建议。

* address.js

'use strict';

module.exports = function (Address) {

    async function getBalanceFromBlockchainInfo(address) {
        const blockchaininfo = Address.app.dataSources.blockchaininfo;
        try {
            const data = await Promise.all([
                blockchaininfo.balance(address),
                blockchaininfo.balance(address)
            ])
            return { "balance": data[0][address]["final_balance"], "unconfirmed_balance": data[0][address]["final_balance"] };
        } catch (err) {
            return err;
        }
    }

    Address.getBalance = function (address, callback) {
        getBalanceFromBlockchainInfo(address).then(data => callback(null, data)).catch(err => callback(err));
    };

    Address.remoteMethod("getBalance", {
        http: { verb: "get", path: "/:address/balances" },
        accepts: [
            { arg: "address", type: "string", required: true }
        ],
        returns: { type: "object", root: true }
    });
};

* datasources.json

{
  "db": {
    "name": "db",
    "connector": "memory"
  },
  "blockchaininfo": {
    "name": "blockchaininfo",
    "connector": "rest",
    "operations": [
      {
        "template": {
          "method": "GET",
          "url": "https://blockchain.info/balance",
          "query": {
            "active": "{address}"
          }
        },
        "functions": {
          "balance": [
            "address"
          ]
        }
      }
    ]
  }
}

https://github.com/y-zono/loopback-connector-rest-example