UNPKG

aisapi

Version:

A JavaScript/TypeScript API library for multiple AI providers

73 lines 2.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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseProvider = void 0; /** * AI服务基类 * 包含共享的基础功能,各服务商只需继承并添加特定实现 */ class BaseProvider { /** * 创建服务实例 * @param options 配置参数 */ constructor(options = {}) { this.apiKey = options.apiKey; this.baseUrl = options.baseUrl || this.getDefaultBaseUrl(); this.timeout = options.timeout || 30000; // 检查密钥是否存在 this.validateApiKey(); } /** * 检查API密钥 */ validateApiKey() { if (!this.apiKey) { console.warn(`[${this.name}] 警告: 没有设置API密钥,部分功能可能无法使用。`); } } /** * 发送HTTP请求的通用方法 */ sendRequest(url, method, body) { return __awaiter(this, void 0, void 0, function* () { const headers = { 'Content-Type': 'application/json' }; if (this.apiKey) { headers['Authorization'] = `Bearer ${this.apiKey}`; } try { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), this.timeout); const response = yield fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined, signal: controller.signal }); clearTimeout(timeoutId); if (!response.ok) { throw new Error(`请求失败: ${response.status} ${response.statusText}`); } return yield response.json(); } catch (e) { if (e instanceof Error) { throw new Error(`[${this.name}] ${e.message}`); } throw e; } }); } } exports.BaseProvider = BaseProvider; //# sourceMappingURL=base.js.map