From 2f628d6d8aede718eb7c1623dffc92525f043c7c Mon Sep 17 00:00:00 2001 From: Leask Wong Date: Sat, 22 Jun 2024 16:24:54 -0400 Subject: [PATCH] handle http fake stream on the frameworks --- lib/universal.mjs | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/lib/universal.mjs b/lib/universal.mjs index 86592bb..b777ac3 100644 --- a/lib/universal.mjs +++ b/lib/universal.mjs @@ -113,6 +113,12 @@ const runtime = { ...options?.headers || {}, }, ...options || {}, }); + webAssert(resp.status !== 401, 'Authentication required.', { + ...optAlert, handler: async () => { + delSignin(); await options?.requireSignin?.(); + } + }); + webAssert(resp.status !== 403, 'Permission denied.', optAlert); if (options?.stream) { switch (resp.status) { case 200: @@ -124,26 +130,34 @@ const runtime = { } break; case 404: - return; + return null; } } - webAssert(resp.status !== 401, 'Authentication required.', { - ...optAlert, handler: async () => { - delSignin(); await options?.requireSignin?.(); - } - }); - webAssert(resp.status !== 403, 'Permission denied.', optAlert); const json = await utilitas.utilitas.ignoreErrFunc(() => resp.json()) || {}; const data = json?.data; webAssert( resp.status < 400 && json && !json.error, json?.error || 'Something went wrong.', optAlert ); - if (options?.stream && [201, 206].includes(resp.status) && data.id) { - setTimeout(async () => await options.stream((await callApi( - `universal/stream/${data.id}`, { t: Date.now() }, - null, { stream: options.stream }))?.content || '' - ), 1000 * 1); + if (options?.stream && resp.status === 201 && data.id) { + data.content = data?.content || ''; + let status = '|'; + const timeout = 60 * 10; // 10 minutes + for (let i = 1; i <= timeout; i++) { + i === timeout && utilitas.utilitas.throwError('Stream timeout.'); + await utilitas.utilitas.timeout(1000 * 1); + if (status === '>') { continue; } + status = '>'; + const resp = await callApi( + `universal/stream/${data.id}`, + { t: Date.now() }, null, { stream: true } + ); + if (resp === null) { break; } + const chunk = resp?.content || ''; + data.content += chunk; + await options.stream(chunk); + status = '|'; + } } return data; },