typed-douyin-openapi
Version:
59 lines • 2.73 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpenapiBase = void 0;
const storage_1 = require("../../api/storage");
const api_base_1 = require("../../api/api_base");
class OpenapiBase extends api_base_1.ApiBase {
constructor(config, tokenStorage) {
super(config.sandbox === true
? 'https://open-sandbox.douyin.com/'
: 'https://developer.toutiao.com/', tokenStorage);
this.appid = config.appid;
this.secret = config.secret;
this.sandbox = config.sandbox || false;
}
getAccessToken() {
return __awaiter(this, void 0, void 0, function* () {
const { expires_in, access_token } = yield this.resolveAccessToken();
// 过期时间,因网络延迟等,将实际过期时间提前10秒,以防止临界点
const expireTime = new Date().getTime() + (expires_in - 10) * 1000;
const token = new storage_1.AccessToken(access_token, expireTime);
yield this.tokenStorage.save(token);
return token;
});
}
ensureAccessToken() {
return __awaiter(this, void 0, void 0, function* () {
const token = yield this.tokenStorage.load();
if (token === null || token === void 0 ? void 0 : token.isValid()) {
return token.accessToken;
}
return (yield this.getAccessToken()).accessToken;
});
}
resolveAccessToken() {
return __awaiter(this, void 0, void 0, function* () {
const result = (yield this.request({
method: 'post',
url: 'api/apps/v2/token',
data: {
grant_type: 'client_credential',
appid: this.appid,
secret: this.secret
}
})).data;
return { access_token: result.access_token, expires_in: result.expires_in };
});
}
}
exports.OpenapiBase = OpenapiBase;
//# sourceMappingURL=openapi_base.js.map
;