瀏覽代碼

chore: mute handle message cut off (#291)

tags/0.3.2
Joel 2 年之前
父節點
當前提交
5f38214a41
No account linked to committer's email address
共有 2 個文件被更改,包括 38 次插入29 次删除
  1. 1
    0
      web/package.json
  2. 37
    29
      web/service/base.ts

+ 1
- 0
web/package.json 查看文件

"i18next-resources-to-backend": "^1.1.3", "i18next-resources-to-backend": "^1.1.3",
"immer": "^9.0.19", "immer": "^9.0.19",
"js-cookie": "^3.0.1", "js-cookie": "^3.0.1",
"katex": "^0.16.7",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"negotiator": "^0.6.3", "negotiator": "^0.6.3",
"next": "13.2.4", "next": "13.2.4",

+ 37
- 29
web/service/base.ts 查看文件

import { API_PREFIX, PUBLIC_API_PREFIX, IS_CE_EDITION } from '@/config'
/* eslint-disable no-new, prefer-promise-reject-errors */
import { API_PREFIX, IS_CE_EDITION, PUBLIC_API_PREFIX } from '@/config'
import Toast from '@/app/components/base/toast' import Toast from '@/app/components/base/toast'


const TIME_OUT = 100000 const TIME_OUT = 100000
}) })
} }



export function format(text: string) { export function format(text: string) {
let res = text.trim() let res = text.trim()
if (res.startsWith('\n')) {
if (res.startsWith('\n'))
res = res.replace('\n', '') res = res.replace('\n', '')
}
return res.replaceAll('\n', '<br/>').replaceAll('```', '') return res.replaceAll('\n', '<br/>').replaceAll('```', '')
} }


lines.forEach((message) => { lines.forEach((message) => {
if (message.startsWith('data: ')) { // check if it starts with data: if (message.startsWith('data: ')) { // check if it starts with data:
// console.log(message); // console.log(message);
bufferObj = JSON.parse(message.substring(6)) // remove data: and parse as json
try {
bufferObj = JSON.parse(message.substring(6)) // remove data: and parse as json
}
catch (e) {
// mute handle message cut off
onData('', isFirstMessage, {
conversationId: bufferObj?.conversation_id,
messageId: bufferObj?.id,
})
return
}
if (bufferObj.status === 400 || !bufferObj.event) { if (bufferObj.status === 400 || !bufferObj.event) {
onData('', false, { onData('', false, {
conversationId: undefined, conversationId: undefined,
messageId: '', messageId: '',
errorMessage: bufferObj.message
errorMessage: bufferObj.message,
}) })
hasError = true hasError = true
onCompleted && onCompleted(true) onCompleted && onCompleted(true)
} }
}) })
buffer = lines[lines.length - 1] buffer = lines[lines.length - 1]
} catch (e) {
}
catch (e) {
onData('', false, { onData('', false, {
conversationId: undefined, conversationId: undefined,
messageId: '', messageId: '',
errorMessage: e + ''
errorMessage: `${e}`,
}) })
hasError = true hasError = true
onCompleted && onCompleted(true) onCompleted && onCompleted(true)
return return
} }
if (!hasError) {
if (!hasError)
read() read()
}
}) })
} }
read() read()
fetchOptions: any, fetchOptions: any,
{ {
isPublicAPI = false, isPublicAPI = false,
needAllResponseContent
}: IOtherOptions
needAllResponseContent,
}: IOtherOptions,
) => { ) => {
const options = Object.assign({}, baseOptions, fetchOptions) const options = Object.assign({}, baseOptions, fetchOptions)
if (isPublicAPI) { if (isPublicAPI) {
options.headers.set('Authorization', `bearer ${sharedToken}`) options.headers.set('Authorization', `bearer ${sharedToken}`)
} }


let urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
let urlWithPrefix = `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}` let urlWithPrefix = `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`


const { method, params, body } = options const { method, params, body } = options
bodyJson.then((data: any) => { bodyJson.then((data: any) => {
if (data.code === 'not_setup') { if (data.code === 'not_setup') {
globalThis.location.href = `${globalThis.location.origin}/install` globalThis.location.href = `${globalThis.location.origin}/install`
} else {
}
else {
if (location.pathname === '/signin') { if (location.pathname === '/signin') {
bodyJson.then((data: any) => { bodyJson.then((data: any) => {
Toast.notify({ type: 'error', message: data.message }) Toast.notify({ type: 'error', message: data.message })
}) })
} else {
}
else {
globalThis.location.href = loginUrl globalThis.location.href = loginUrl
} }
} }
new Promise(() => { new Promise(() => {
bodyJson.then((data: any) => { bodyJson.then((data: any) => {
Toast.notify({ type: 'error', message: data.message }) Toast.notify({ type: 'error', message: data.message })
if (data.code === 'already_setup') {
if (data.code === 'already_setup')
globalThis.location.href = `${globalThis.location.origin}/signin` globalThis.location.href = `${globalThis.location.origin}/signin`
}
}) })
}) })
break break
// fall through // fall through
default: default:
// eslint-disable-next-line no-new
new Promise(() => { new Promise(() => {
bodyJson.then((data: any) => { bodyJson.then((data: any) => {
Toast.notify({ type: 'error', message: data.message }) Toast.notify({ type: 'error', message: data.message })


// handle delete api. Delete api not return content. // handle delete api. Delete api not return content.
if (res.status === 204) { if (res.status === 204) {
resolve({ result: "success" })
resolve({ result: 'success' })
return return
} }


...defaultOptions, ...defaultOptions,
...options, ...options,
headers: { ...defaultOptions.headers, ...options.headers }, headers: { ...defaultOptions.headers, ...options.headers },
};
return new Promise(function (resolve, reject) {
}
return new Promise((resolve, reject) => {
const xhr = options.xhr const xhr = options.xhr
xhr.open(options.method, options.url);
for (const key in options.headers) {
xhr.setRequestHeader(key, options.headers[key]);
}
xhr.open(options.method, options.url)
for (const key in options.headers)
xhr.setRequestHeader(key, options.headers[key])
xhr.withCredentials = true xhr.withCredentials = true
xhr.responseType = 'json' xhr.responseType = 'json'
xhr.onreadystatechange = function () { xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { if (xhr.readyState === 4) {
if (xhr.status === 201) {
if (xhr.status === 201)
resolve(xhr.response) resolve(xhr.response)
} else {
else
reject(xhr) reject(xhr)
}
} }
} }
xhr.upload.onprogress = options.onprogress xhr.upload.onprogress = options.onprogress
.then((res: any) => { .then((res: any) => {
// debugger // debugger
if (!/^(2|3)\d{2}$/.test(res.status)) { if (!/^(2|3)\d{2}$/.test(res.status)) {
// eslint-disable-next-line no-new
new Promise(() => { new Promise(() => {
res.json().then((data: any) => { res.json().then((data: any) => {
Toast.notify({ type: 'error', message: data.message || 'Server Error' }) Toast.notify({ type: 'error', message: data.message || 'Server Error' })

Loading…
取消
儲存