Skip to content

Commit

Permalink
handle http fake stream on the frameworks
Browse files Browse the repository at this point in the history
  • Loading branch information
Leask committed Jun 22, 2024
1 parent 2fc9e18 commit 2f628d6
Showing 1 changed file with 26 additions and 12 deletions.
38 changes: 26 additions & 12 deletions lib/universal.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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;
},
Expand Down

0 comments on commit 2f628d6

Please sign in to comment.