【发布时间】:2015-12-07 10:13:55
【问题描述】:
如何在 Loopback 上创建外部 API?
我想获取外部 API 数据并将其用于我的环回应用程序,并将来自环回的输入传递给外部 API 并返回结果或响应。
【问题讨论】:
标签: api loopbackjs
如何在 Loopback 上创建外部 API?
我想获取外部 API 数据并将其用于我的环回应用程序,并将来自环回的输入传递给外部 API 并返回结果或响应。
【问题讨论】:
标签: api loopbackjs
Loopback 有non-database connectors 的概念,包括REST connector。来自文档:
LoopBack 支持许多连接到后端系统的连接器 数据库。
这些类型的连接器通常根据具体情况实现特定的方法 在底层系统上。例如,REST 连接器委托 在 Push 连接器与 iOS 集成时调用 REST API 和 Android 推送通知服务。
如果您发布有关要调用的 API 调用的详细信息,那么我可以为您添加一些更具体的代码示例。同时,这也来自文档:
datasources.json
MyModel": {
"name": "MyModel",
"connector": "rest",
"debug": false,
"options": {
"headers": {
"accept": "application/json",
"content-type": "application/json"
},
"strictSSL": false
},
"operations": [
{
"template": {
"method": "GET",
"url": "http://maps.googleapis.com/maps/api/geocode/{format=json}",
"query": {
"address": "{street},{city},{zipcode}",
"sensor": "{sensor=false}"
},
"options": {
"strictSSL": true,
"useQuerystring": true
},
"responsePath": "$.results[0].geometry.location"
},
"functions": {
"geocode": ["street", "city", "zipcode"]
}
}
]
}
然后您可以使用以下代码从代码中调用此 api:
app.dataSources.MyModel.geocode('107 S B St', 'San Mateo', '94401', processResponse);
【讨论】:
你需要https 模块来调用环回中的外部模块。
假设您想将外部 API 与任何模型脚本文件一起使用。让模型名称为Customer
在您的回送文件夹中。键入此命令并安装 https 模块。
$npm install https --save
common/models/customer.js
var https = require('https');
Customer.externalApiProcessing = function(number, callback){
var data = "https://rest.xyz.com/api/1";
https.get(
data,
function(res) {
res.on('data', function(data) {
// all done! handle the data as you need to
/*
DO SOME PROCESSING ON THE `DATA` HERE
*/
enter code here
//Finally return the data. the return type should be an object.
callback(null, data);
});
}
).on('error', function(err) {
console.log("Error getting data from the server.");
// handle errors somewhow
callback(err, null);
});
}
//Now registering the method
Customer.remoteMethod(
'extenalApiProcessing',
{
accepts: {arg: 'number', type: 'string', required:true},
returns: {arg: 'myResponse', type: 'object'},
description: "A test for processing on external Api and then sending back the response to /externalApiProcessing route"
}
)
common/models/customer.json
....
....
//Now add this line in the ACL property.
"acls": [
{
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW",
"property": "extenalApiProcessing"
}
]
现在在 /api/modelName/extenalApiProcessing 探索 api
默认为post method。
了解更多信息。 Loopback Remote Methods
【讨论】: