@coze/uniapp-api
Version:
Official Coze UniApp SDK for seamless AI integration into your applications | 扣子官方 UniApp SDK,助您轻松集成 AI 能力到应用中
76 lines (75 loc) • 2.33 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventSource = void 0;
const types_1 = require("./types");
const base_1 = require("./base");
/**
* 为字节跳动小程序处理流式请求
* Process streaming requests for ByteDance Mini Program
*/
class EventSource extends base_1.BaseEventSource {
constructor(options) {
super();
Object.defineProperty(this, "options", {
enumerable: true,
configurable: true,
writable: true,
value: options
});
Object.defineProperty(this, "task", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
Object.defineProperty(this, "isAborted", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
}
start() {
const { url, method, headers, data, timeout } = this.options;
if (!tt.createEventSource) {
this.trigger(types_1.EventName.Fail, {
errMsg: 'createEventSource is not supported',
});
return;
}
this.task = tt.createEventSource({
url,
method,
header: headers,
data,
timeout,
});
this.task.onOpen(() => {
this.trigger(types_1.EventName.Open);
});
this.task.onMessage(msg => {
this.trigger(types_1.EventName.Chunk, { data: msg });
});
this.task.onError(e => {
var _a;
const errMsg = e instanceof Error ? e.message : ((_a = (e && e.errMsg)) !== null && _a !== void 0 ? _a : 'fail');
if (this.isAborted) {
return;
}
this.trigger(types_1.EventName.Fail, { errMsg });
});
this.task.onClose(() => {
this.trigger(types_1.EventName.Success);
});
}
abort() {
var _a;
if (!this.isAborted) {
this.isAborted = true;
(_a = this.task) === null || _a === void 0 ? void 0 : _a.close();
// 手动触发"fail"事件
this.trigger(types_1.EventName.Fail, { errMsg: 'abort' });
}
}
}
exports.EventSource = EventSource;