uniapp stream 流式数据请求方法封装 uninapp 模拟 fetch 请求

/**
 * uniapp stream 流式数据请求方法封装
 * npm install @escook/request-miniprogram
 * 
 * 使用示例
 * 
        import { uniFetch } from '@/utils/common';
        let url = '/house/app/coll/layer/collYard/stream';
	uniFetch(url, (data) => {
		console.log('=>',data);
	  this.data = this.data.concat(data);
	});
    	
**/
export async function uniFetch(url, onData) {
  $http.baseUrl = 'https://xuncha.xiaoguan.net/xuncha/prod-api';	
  try {
	const res = await $http.get(url, {
	  header: { 'Accept': 'application/x-ndjson' }, // 假设后端返回 NDJSON
	});

	if (res.statusCode === 200) {
	  const dataString = res.data;
	  // 处理可能没有换行符的情况
	  if (typeof dataString === 'string' && dataString.trim()) {
		const lines = dataString.split('\n');
		lines.forEach(line => {
		  if (line.trim()) {
			try {
			  const data = JSON.parse(line);
			  onData(data); // 逐条处理数据
			} catch (e) {
			  console.error('解析失败:', line);
			}
		  }
		});
		// 额外检查最后一行是否为空(处理没有尾随换行符的情况)
		const lastLine = lines[lines.length - 1];
		if (lastLine && lastLine.trim()) {
		  try {
			const data = JSON.parse(lastLine);
			onData(data);
		  } catch (e) {
			console.error('解析最后一行失败:', lastLine);
		  }
		}
	  }else{
		  if(typeof(dataString) === 'object'){
			   onData(dataString);
		  }
	  }
	  
	}
  } catch (err) {
	console.error('请求失败:', err);
  }
}