(res: Response, fallback: T, onProgress?: (p: ImportProgress) => void)
| 20 | import { get, fetchWithAuth, getBaseUrl } from '../utils/http' |
| 21 | |
| 22 | async function consumeSseStream<T>(res: Response, fallback: T, onProgress?: (p: ImportProgress) => void): Promise<T> { |
| 23 | const reader = res.body?.getReader() |
| 24 | if (!reader) return fallback |
| 25 | |
| 26 | const decoder = new TextDecoder() |
| 27 | let buffer = '' |
| 28 | let result: T = fallback |
| 29 | |
| 30 | while (true) { |
| 31 | const { done, value } = await reader.read() |
| 32 | if (done) break |
| 33 | |
| 34 | buffer += decoder.decode(value, { stream: true }) |
| 35 | const lines = buffer.split('\n') |
| 36 | buffer = lines.pop() || '' |
| 37 | |
| 38 | let eventType = '' |
| 39 | for (const line of lines) { |
| 40 | if (line.startsWith('event: ')) { |
| 41 | eventType = line.slice(7).trim() |
| 42 | } else if (line.startsWith('data: ')) { |
| 43 | const data = JSON.parse(line.slice(6)) |
| 44 | if (eventType === 'progress') { |
| 45 | onProgress?.(data as ImportProgress) |
| 46 | } else if (eventType === 'done' || eventType === 'error') { |
| 47 | result = data as T |
| 48 | } |
| 49 | eventType = '' |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | return result |
| 55 | } |
| 56 | |
| 57 | export class FetchImportAdapter implements ImportAdapter { |
| 58 | async importFile( |
no test coverage detected