@coze/uniapp-api
Version:
Official Coze UniApp SDK for seamless AI integration into your applications | 扣子官方 UniApp SDK,助您轻松集成 AI 能力到应用中
64 lines (63 loc) • 2.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendRequest = sendRequest;
const api_1 = require("@coze/api");
const async_1 = require("../helpers/async");
const types_1 = require("./types");
const index_weapp_1 = require("./index.weapp");
const index_tt_1 = require("./index.tt");
const index_1 = require("./index");
// 根据UniApp环境选择合适的EventSource实现
const getEventSource = () => {
// 如果在web环境,返回默认EventSource
if (typeof uni === 'undefined' ||
uni.getSystemInfoSync().uniPlatform === 'web') {
return index_1.EventSource;
}
// 根据系统信息判断平台类型
const systemInfo = uni.getSystemInfoSync();
if (systemInfo.hostName === 'Douyin' || systemInfo.hostName === 'Toutiao') {
return index_tt_1.EventSource;
}
else if (systemInfo.hostName === 'WeChat') {
return index_weapp_1.EventSource;
}
// 默认返回标准EventSource
return index_1.EventSource;
};
// 使用函数调用以便每次都获取最新环境
const ES = getEventSource();
function sendRequest(config, result) {
var _a, _b;
result.deferred = new async_1.Deferred();
result.done = false;
const eventSource = new ES(config)
.on(types_1.EventName.Chunk, msg => {
var _a;
result.messages.push(msg.data);
(_a = result.deferred) === null || _a === void 0 ? void 0 : _a.resolve(msg.data);
result.deferred = new async_1.Deferred();
})
.on(types_1.EventName.Success, msg => {
var _a;
result.done = true;
(_a = result.deferred) === null || _a === void 0 ? void 0 : _a.resolve(msg);
})
.on(types_1.EventName.Fail, msg => {
var _a, _b;
const data = msg.data || {};
data.error = data.error || data.detail;
const error = api_1.APIError.generate(200, data, msg.errMsg, {
'x-tt-logid': (_a = data.error) === null || _a === void 0 ? void 0 : _a.logid,
});
result.done = true;
result.error = error;
(_b = result.deferred) === null || _b === void 0 ? void 0 : _b.reject(error);
});
if (config.signal) {
(_b = (_a = config.signal).addEventListener) === null || _b === void 0 ? void 0 : _b.call(_a, 'abort', () => {
eventSource.abort();
});
}
eventSource.start();
}