@toowe/streaminghttp
v1.0.10
Published
streaming http request
Downloads
9
Readme
基于fetch长连接方式的流式数据Http封装
1、初始化client
const http = new StreamingHttp();
const requestInterceptor = (url: string, headers: Record<string, string>) => {
headers.Authorization = 'Bearer ' + token;
return { url, headers };
}
const responseInterceptor = (packet: ResponsePacket) => {
if (packet.code !== 200) {
throw new Error(packet.message || '流式数据包未知异常');
}
return packet;
}
const responseErrorInterceptor = (error: Error) => {
console.error(error);
return error
}
http.addRequestInterceptor(requestInterceptor)
.addResponseInterceptor(responseInterceptor)
.addResponseErrorInterceptor(responseErrorInterceptor);
// 提供了默认的拦截器
import { defaultRequestInterceptor, defaultResponseInterceptor, defaultResponseErrorInterceptor } from '@toowe/streaminghttp';
http.addRequestInterceptor(defaultRequestInterceptor)
.addResponseInterceptor(defaultResponseInterceptor)
.addResponseErrorInterceptor(defaultResponseErrorInterceptor);
2、定义传输实体和对应的处理器
class ChatMessage {
// command字段用于区分不同的消息类型,跟后端约定好
static command = 'chat';
content: string;
parse(data: any) {
this.content = data.content;
}
}
function chatMessageHandler(message: ChatMessage) {
console.log(message.content);
}
// 支持数组形式的实体
function chatMessageHandler(messages: ChatMessage[]) {
console.log(messages.length);
}
function otherMessageHandler(message: any) {
console.log(message);
}
3、发送请求
const url = 'http://localhost:3000/streaming';
const params = {};
http.request(url, params).command(ChatMessage, chatMessageHandler).command(otherMessageHandler);
4、附加功能
const request = http.request(url);
// 取消请求
request.cancel();
// 等待请求完成
await request.wait();