forchange-api
Version:
A sdk of forchange api.
88 lines (82 loc) • 2.1 kB
JavaScript
const Promise = require('bluebird');
const APIs = require('st-api').APIs;
const HttpClient = require('st-api').HttpClient;
const StatusCode = require('./common/status-code');
class TokenModel {
constructor(opts) {
this.appid = opts.appid;
this.secret = opts.secret;
this.tokenExpires = opts.tokenExpires || 3600000;
if (opts.api) {
this.tokenApi = opts.api;
} else {
let config = {
defaultHost: opts.host,
token: {
pathname: '/api/v1/auth',
method: 'post',
type: 'form'
}
};
let apis = new APIs(config, new HttpClient());
this.tokenApi = apis.token;
}
// 以下几个属性应当是私有,但 es6 class 不支持私有属性,所以暂时先这么写
// 不要随意修改这几个属性!不要随意修改这几个属性!不要随意修改这几个属性!
this.token = null;
this.oldToken = null;
this.lastUpdateTime = null;
this.getToken();
Object.defineProperties(this, {
appid: {
configurable: false,
writable: false,
},
secret: {
configurable: false,
writable: false,
},
tokenExpires: {
configurable: false,
writable: false,
},
tokenApi: {
configurable: false,
writable: false,
},
});
}
isExpired() {
const currentTime = (new Date())
.getTime();
return !this.token || this.lastUpdateTime + this.tokenExpires - 12000 <
currentTime;
}
getToken() {
if (this.isExpired()) {
return this.tokenApi.post({
appid: this.appid,
secret: this.secret,
})
.then(data => {
const dataObj = data;
if (dataObj.error) {
throw new Error(
`An error occured when request token api: ${dataObj.error}`);
} else if (dataObj.status_code === StatusCode.TOKEN_EXPIRED) {
throw new Error(`Token has been expired: ${dataObj.message}`);
}
this.oldToken = this.token;
this.token = dataObj.token;
this.lastUpdateTime = (new Date())
.getTime();
return this.token;
});
}
return Promise.resolve(this.token);
}
getOldToken() {
return this.oldToken;
}
}
module.exports = TokenModel;