我目前正在尝试连接到 Artsy public API我遇到了一些麻烦。请对我宽容一点,我是 NodeJS 和 SailsJS 的新手。我创建了一个名为 api/services/Artsy.js 的文件,现在我很想知道我的方法(见下文)是否真的是 Sails 的做事方式。这是一个问题。如果没有,在 SailsJS 中设置对 API 的基本调用的正确方法是什么?或者更具体地说,Artsy API?
想到的问题:
我需要等到检索到 token 后才能调用需要它的 API 方法。这是通过 pubsub 还是其他技术完成的。有没有实际的例子来展示它在 SailsJS 中是如何工作的?
您可以在 View 内使用服务调用吗?如何?这还有道理吗?看起来它对于 API 调用可能很有用。
注意:我已经设置了包含重要变量的文件 config/artsy.js。 (见下文)
/api/services/Artsy.js
/**
*
* Artsy.js => in api/services
* @description A service that connects to the Artsy.net public API.
* @url https://developers.artsy.net/
**/
var request = require('superagent'),
traverson = require('traverson'),
xappToken;
module.exports = {
init: function(){
sails.log.info('----- Artsy API Initialized -----');
var clientID = sails.config.artsy.clientId,
clientSecret = sails.config.artsy.clientSecret,
apiTokenUrl = sails.config.artsy.apiTokenUrl;
try{
request
.post(apiTokenUrl)
.send({ client_id: clientID, client_secret: clientSecret })
.end(function(res) {
if (res) {
xappToken = res.body.token;
} else {
sails.log.error('api/services/Artsy.js:');
sails.log.error(res.text);
}
});
} catch(e) {
sails.log.error('api/services/Artsy.js:');
sails.log.error(e);
}
},
getArtistStatement: function(){
var api = traverson.jsonHal.from(sails.config.artsy.apiUrl);
var request = api.newRequest()
.follow('artist')
.withRequestOptions({
headers: {
'X-Xapp-Token': xappToken,
'Accept': 'application/vnd.artsy-v2+json'
}
})
.withTemplateParameters({ id: 'andy-warhol' })
.getResource(function(error, andyWarhol) {
console.log(andyWarhol.name + 'was born in ' + andyWarhol.birthday + ' in ' + andyWarhol.hometown);
});
}
};
/config/artsy.js
/**
* artsy.js
*
* @description :: This is the brains that allow the app to connect to artsy.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports.artsy = {
clientId: 'CLIENT_ID',
clientSecret: 'CLIENT_SECRET',
apiUrl: 'https://api.artsy.net/api',
apiTokenUrl: 'https://api.artsy.net/api/tokens/xapp_token'
};
最佳答案
如果我正确理解你的问题,那么
That's one question. If not, what is the proper way to set up a basic call to an API in SailsJS?
服务对于这种情况来说是非常合适的地方。 您可以在 config/bootstrap.js 中调用 init 方法,或者在用户登录或其他地方调用 init 方法。
I need to wait until the token is retrieved before I can call an API method that requires it. Is this done via pubsub
是的,你可以使用 pubsub,但使用 Promise 似乎更好。例如,您可以使用这个库 https://github.com/istavros/vowjs
Can you use service calls inside of views? How? Does this even make sense? It seems like it might be useful for an API call.
我想是的,但看来你不应该想要它。当模板只使用 Controller 传递的数据而不使用其他任何东西时,它看起来很不错。因此,在 Controller (或 mb 模型)中使用服务,然后将结果传递给模板。
关于javascript - 连接 API 的 SailsJS 方式。最好的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26289154/