UNPKG

typed-douyin-openapi

Version:
79 lines 3.77 kB
"use strict"; 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()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ApiBase = void 0; const storage_1 = require("./storage"); const axios_1 = __importDefault(require("axios")); const errors_1 = require("../errors"); class ApiBase { constructor(baseURL, tokenStorage) { this.logger = () => { }; this.tokenStorage = tokenStorage || new storage_1.MemoryTokenStorage(); this.axiosInstance = axios_1.default.create({ baseURL: baseURL, timeout: 12000, headers: { 'Content-Type': 'application/json' } }); } request(opts, retry = 3) { var _a, _b, _c; return __awaiter(this, void 0, void 0, function* () { opts.method = opts.method || 'get'; try { const res = yield this.axiosInstance.request(opts); this.logger('DouyinRequest', opts, res.data); if (res.status < 200 || res.status > 204) { throw new errors_1.DouyinAPIError(`url: ${opts.url}, status code: ${res.status}`, -1); } const { err_no, err_msg, err_tips } = res.data; if (!err_no) { return res.data; } if ([12024, 12025].indexOf(err_no) != -1 && retry > 0) { // Token错误/过期, 重新获取 yield this.tokenStorage.save(null); return this.request(opts, retry - 1); } else { throw new errors_1.DouyinAPIError(err_tips || err_msg, err_no); } } catch (error) { console.error('ErrorRequest:', opts.url, new Date()); if (error instanceof errors_1.DouyinAPIError) { throw error; } else if (error.response) { console.error('ErrorRequest', opts, new Date()); throw new errors_1.DouyinAPIError(((_a = error.response.data) === null || _a === void 0 ? void 0 : _a.err_tips) || ((_b = error.response.data) === null || _b === void 0 ? void 0 : _b.err_msg) || '服务器内部错误', ((_c = error.response.data) === null || _c === void 0 ? void 0 : _c.err_no) || error.response.status); } else if (error.request) { throw new errors_1.DouyinAPIError('请求超时,请检查网络', -406); } else if (typeof error.err_no === 'undefined') { throw new errors_1.DouyinAPIError('请求失败,请稍后再试', -400); } else { throw new errors_1.DouyinAPIError('未知错误', -500); } } }); } } exports.ApiBase = ApiBase; //# sourceMappingURL=api_base.js.map