UNPKG

workplus-api

Version:
116 lines (99 loc) 2.88 kB
/** * Created by luomin on 16/7/6. */ 'use strict'; let request = require('request'); let Constant = require('./constant'); const MAX_RETRY_NUM = 3; let CURRENT_RETRY_NUM = 0; let accessToken = null; let requestFail = function (err, body) { if (err) { console.error('申请token失败: ', err); return true; } return body.status !== Constant.HTTP_SUCCESS; } let resetCurrentRetryNum = function () { CURRENT_RETRY_NUM = 0; } let requestToken = function (config, success, fail) { request.post({ url: `${config.api}/token`, json: true, body: { grant_type: 'client_credentials', scope: 'app', domain_id: config.domain, client_id: config.key, client_secret: config.secret, org_id: config.orgId } }, (err, r, body) => { console.log('申请token接口返回: ', body); if (requestFail(err, body)) { retryApplyAccessToken(config, success, fail); return; } resetCurrentRetryNum(); success(body.result.access_token); }); } let applyAccessToken = function (config) { return new Promise(function (resolve, reject) { requestToken(config, resolve, reject); }); } let retryApplyAccessToken = function (config, success, fail) { if (CURRENT_RETRY_NUM >= MAX_RETRY_NUM) { console.log('超过最大重试申请token次数, 申请失败'); fail(); return; } console.log(`尝试第${CURRENT_RETRY_NUM + 1}次重新申请token`); CURRENT_RETRY_NUM += 1; requestToken(config, success, fail); } let _instance = (function () { let instance = null; return newInstance => { if (newInstance) { instance = newInstance; } return instance; } }()); class Token { constructor(config) { if (_instance()) { return _instance(); } this.config = config; applyAccessToken(config).then(accessToken => { this.accessToken = accessToken; }).catch(() => { console.log('申请token失败'); }); _instance(this); } getToken() { return this.accessToken; } static assembleRequestURL(path) { if (path.indexOf('?') > -1) { return `${_instance().config.api}/${path}&access_token=${_instance().accessToken}`; } return `${_instance().config.api}/${path}?access_token=${_instance().accessToken}`; } static reset() { applyAccessToken(_instance().config).then((accessToken) => { _instance().accessToken = accessToken; }).catch(() => { console.log('申请token失败'); }); } static getOrgId() { return _instance().config.orgId; } } module.exports = Token;