我正在制作一些与API交互的代码, 为了使用API,您需要获取用于其余请求的会话密钥,会话密钥在一段时间后将变为无效,因此代码也需要准备好接受reauth。
代码本身与API无关,因为它是关于如何设计代码流的问题,我正在寻找最好的方法。
我这里没有代码(javascript / node.js),但这里基本上是伪代码的样子:
function getResult {
data = foobar
return getData(data, callback)
}
function getData(data, callback) {
*building query (including the session-key) and getting data via http*
if error == noauth
auth()
// What should happen here, I need to rerun the query
else
callback(result)
}
function auth {
data = foobar
getData(data, callback(?))
// it returns a session-key to use
//What should happen here?
}
答案 0 :(得分:0)
我会做类似的事情:
function GetAuth(auth_params)
{
// get session key
return session key;
}
function MyAPIWorker(auth_params)
{
this._auth_params = auth_params;
this._current_auth = null;
}
MyAPIWorker.prototype.do(action)
{
if (this._current_auth == null)
{
this._current_auth = GetAuth();
}
var result = action(this._current_auth);
if (result == no_auth_error)
{
this._current_auth = GetAuth();
result = action(this._current_auth);
}
return result;
}
然后使用它:
worker = new MyAPIWorker(/* auth params here */);
worker.do(function (sessionKey) { /* do something with session key */});
/** blah blah **/
worker.do(function (sessionKey) { /* do other something with session key */});
工人将为你处理所有繁重的工作......