t-comm
Version:
专业、稳定、纯粹的工具库
87 lines (84 loc) • 2.88 kB
JavaScript
import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../../tslib.es6-848120af.js';
import axios from 'axios';
var tokenMap = {};
/**
* 获取凭据的通用代码
* @ignore
*
* @param {object} options 配置
* @param {string} options.apiKey apiKey
* @param {string} options.loginName loginName
* @param {Function} options.getPwdCode getPwdCode
* @param {Function} options.encrypt encrypt
*
* @returns {Promise<{auth: string, apiToken: string, apiTime: string}>} 凭据信息
* @example
* ```ts
* const { auth, apiToken, apiTime } = await getCredential({
* apiKey: 'xxx',
* loginName: 'novlan1',
* getPwdCode: (apiKey, apiToken, apiTime) => '<sign>',
* encrypt: (apiKey, loginName) => '<encrypted>',
* });
* ```
*/
function getCredential(_ref) {
var apiKey = _ref.apiKey,
loginName = _ref.loginName,
getPwdCode = _ref.getPwdCode,
encrypt = _ref.encrypt;
var _a, _b;
return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
var uniqueKey, res, _ref2, apiTime, apiToken, result, _t;
return _regeneratorRuntime.wrap(function (_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
uniqueKey = "".concat(loginName, "-").concat(apiKey);
if (!tokenMap[uniqueKey]) {
_context.next = 1;
break;
}
return _context.abrupt("return", tokenMap[uniqueKey]);
case 1:
_context.next = 2;
return axios({
method: 'POST',
url: '/api/interface/getApiToken',
data: {
isFresh: 0,
loginName: loginName,
apiKey: encrypt(apiKey, loginName)
}
});
case 2:
res = _context.sent;
if (!((_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.retcode)) {
_context.next = 3;
break;
}
console.warn(res.data);
throw new Error('获取凭据失败!');
case 3:
_ref2 = ((_b = res === null || res === void 0 ? void 0 : res.data) === null || _b === void 0 ? void 0 : _b.data) || {}, apiTime = _ref2.api_time, apiToken = _ref2.api_token;
result = {
auth: getPwdCode(apiKey, apiToken, +apiTime),
apiToken: apiToken,
apiTime: apiTime
};
tokenMap[uniqueKey] = result;
return _context.abrupt("return", result);
case 4:
_context.prev = 4;
_t = _context["catch"](0);
console.warn(_t);
throw new Error('获取凭据失败!');
case 5:
case "end":
return _context.stop();
}
}, _callee, null, [[0, 4]]);
}));
}
export { getCredential };