mirror of
https://github.com/SillyTavern/SillyTavern.git
synced 2025-06-05 21:59:27 +02:00
Properly forward status codes from streams
This commit is contained in:
@@ -1,9 +1,8 @@
|
||||
const fetch = require('node-fetch').default;
|
||||
const express = require('express');
|
||||
const util = require('util');
|
||||
const { Readable } = require('stream');
|
||||
const { readSecret, SECRET_KEYS } = require('./secrets');
|
||||
const { readAllChunks, extractFileFromZipBuffer } = require('../util');
|
||||
const { readAllChunks, extractFileFromZipBuffer, forwardFetchResponse } = require('../util');
|
||||
const { jsonParser } = require('../express-common');
|
||||
|
||||
const API_NOVELAI = 'https://api.novelai.net';
|
||||
@@ -188,17 +187,7 @@ router.post('/generate', jsonParser, async function (req, res) {
|
||||
|
||||
if (req.body.streaming) {
|
||||
// Pipe remote SSE stream to Express response
|
||||
response.body.pipe(res);
|
||||
|
||||
req.socket.on('close', function () {
|
||||
if (response.body instanceof Readable) response.body.destroy(); // Close the remote stream
|
||||
res.end(); // End the Express response
|
||||
});
|
||||
|
||||
response.body.on('end', function () {
|
||||
console.log('Streaming request finished');
|
||||
res.end();
|
||||
});
|
||||
forwardFetchResponse(response, res);
|
||||
} else {
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
|
23
src/util.js
23
src/util.js
@@ -6,6 +6,7 @@ const yauzl = require('yauzl');
|
||||
const mime = require('mime-types');
|
||||
const yaml = require('yaml');
|
||||
const { default: simpleGit } = require('simple-git');
|
||||
const { Readable } = require('stream');
|
||||
|
||||
const { DIRECTORIES } = require('./constants');
|
||||
|
||||
@@ -346,6 +347,27 @@ function getImages(path) {
|
||||
.sort(Intl.Collator().compare);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pipe a fetch() response to an Express.js Response, including status code.
|
||||
* @param {Response} from The Fetch API response to pipe from.
|
||||
* @param {Express.Response} to The Express response to pipe to.
|
||||
*/
|
||||
function forwardFetchResponse(from, to) {
|
||||
to.statusCode = from.status;
|
||||
to.statusMessage = from.statusText;
|
||||
from.body.pipe(to);
|
||||
|
||||
to.socket.on('close', function () {
|
||||
if (from.body instanceof Readable) from.body.destroy(); // Close the remote stream
|
||||
to.end(); // End the Express response
|
||||
});
|
||||
|
||||
from.body.on('end', function () {
|
||||
console.log('Streaming request finished');
|
||||
to.end();
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getConfig,
|
||||
getConfigValue,
|
||||
@@ -365,4 +387,5 @@ module.exports = {
|
||||
generateTimestamp,
|
||||
removeOldBackups,
|
||||
getImages,
|
||||
forwardFetchResponse,
|
||||
};
|
||||
|
Reference in New Issue
Block a user