| 9 | let tempResult = '' |
| 10 | |
| 11 | const write_stream = async () => { |
| 12 | try { |
| 13 | while (true) { |
| 14 | const { done, value } = await reader.read() |
| 15 | |
| 16 | if (done) { |
| 17 | ChatManagement.close(chat.id) |
| 18 | return |
| 19 | } |
| 20 | |
| 21 | const decoder = new TextDecoder('utf-8') |
| 22 | let str = decoder.decode(value, { stream: true }) |
| 23 | |
| 24 | tempResult += str |
| 25 | const split = tempResult.match(/data:.*?}\n\n/g) |
| 26 | if (split) { |
| 27 | str = split.join('') |
| 28 | tempResult = tempResult.replace(str, '') |
| 29 | |
| 30 | // 批量处理所有 chunk |
| 31 | for (const item of split) { |
| 32 | const chunk = JSON.parse(item.replace('data:', '')) |
| 33 | chat.chat_id = chunk.chat_id |
| 34 | chat.record_id = chunk.chat_record_id |
| 35 | |
| 36 | if (!chunk.is_end) { |
| 37 | ChatManagement.appendChunk(chat.id, chunk) |
| 38 | } |
| 39 | |
| 40 | if (chunk.is_end) { |
| 41 | return Promise.resolve() |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | // 如果没有匹配到完整chunk,继续读取下一块 |
| 46 | } |
| 47 | } catch (e) { |
| 48 | return Promise.reject(e) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | const write_json = async () => { |
| 53 | try { |