Reputation: 8584
I'm trying to make an example app with connector-rest.
https://github.com/strongloop/loopback-connector-rest
My goal is making the following api.
$ curl http://localhost:3001/addresses/17F54d4S9aLpvUEsk7MkYWafmzxJhhb9wW/balance
{
"balance": 42030
}
The balance is retrieved from blockchain.info api.
$ curl https://blockchain.info/balance?active=17F54d4S9aLpvUEsk7MkYWafmzxJhhb9wW
{"17F54d4S9aLpvUEsk7MkYWafmzxJhhb9wW": {
"final_balance": 42030,
"n_tx": 2,
"total_received": 42030
}}
The followings are what I've done.
But I don't know what should I do next? I think I need to configure something for request. Should I add it into datasources.json? How to call it from addresses.js?
My code is saved on github. https://github.com/y-zono/loopback-connector-rest-example
Update 1
I found this example.
https://github.com/strongloop-community/loopback-example-connector/tree/rest
Then, I could fetch data from blockchain.info.
Still not sure whether this is normal way or not. I'm checking about that.
Upvotes: 0
Views: 529
Reputation: 8584
I found it and I confirmed Promise and async/await work well.
Any suggestions are welcome and appreciated when you have any other better ways.
*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
Upvotes: 1