我正在尝试使用带有连接器支架的示例应用程序。
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
}}
以下是我所做的。
但是我不知道下一步该怎么做?我想我需要配置一些请求。我应该将其添加到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获取数据。
仍然不确定这是否是正常方法。我正在检查。
答案 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"
]
}
}
]
}
}