base.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. import { refreshAccessTokenOrRelogin } from './refresh-token'
  2. import { API_PREFIX, IS_CE_EDITION, PUBLIC_API_PREFIX } from '@/config'
  3. import Toast from '@/app/components/base/toast'
  4. import type { AnnotationReply, MessageEnd, MessageReplace, ThoughtItem } from '@/app/components/base/chat/chat/type'
  5. import type { VisionFile } from '@/types/app'
  6. import type {
  7. IterationFinishedResponse,
  8. IterationNextResponse,
  9. IterationStartedResponse,
  10. NodeFinishedResponse,
  11. NodeStartedResponse,
  12. ParallelBranchFinishedResponse,
  13. ParallelBranchStartedResponse,
  14. TextChunkResponse,
  15. TextReplaceResponse,
  16. WorkflowFinishedResponse,
  17. WorkflowStartedResponse,
  18. } from '@/types/workflow'
  19. import { removeAccessToken } from '@/app/components/share/utils'
  20. import { asyncRunSafe } from '@/utils'
  21. const TIME_OUT = 100000
  22. const ContentType = {
  23. json: 'application/json',
  24. stream: 'text/event-stream',
  25. audio: 'audio/mpeg',
  26. form: 'application/x-www-form-urlencoded; charset=UTF-8',
  27. download: 'application/octet-stream', // for download
  28. upload: 'multipart/form-data', // for upload
  29. }
  30. const baseOptions = {
  31. method: 'GET',
  32. mode: 'cors',
  33. credentials: 'include', // always send cookies、HTTP Basic authentication.
  34. headers: new Headers({
  35. 'Content-Type': ContentType.json,
  36. }),
  37. redirect: 'follow',
  38. }
  39. export type IOnDataMoreInfo = {
  40. conversationId?: string
  41. taskId?: string
  42. messageId: string
  43. errorMessage?: string
  44. errorCode?: string
  45. }
  46. export type IOnData = (message: string, isFirstMessage: boolean, moreInfo: IOnDataMoreInfo) => void
  47. export type IOnThought = (though: ThoughtItem) => void
  48. export type IOnFile = (file: VisionFile) => void
  49. export type IOnMessageEnd = (messageEnd: MessageEnd) => void
  50. export type IOnMessageReplace = (messageReplace: MessageReplace) => void
  51. export type IOnAnnotationReply = (messageReplace: AnnotationReply) => void
  52. export type IOnCompleted = (hasError?: boolean, errorMessage?: string) => void
  53. export type IOnError = (msg: string, code?: string) => void
  54. export type IOnWorkflowStarted = (workflowStarted: WorkflowStartedResponse) => void
  55. export type IOnWorkflowFinished = (workflowFinished: WorkflowFinishedResponse) => void
  56. export type IOnNodeStarted = (nodeStarted: NodeStartedResponse) => void
  57. export type IOnNodeFinished = (nodeFinished: NodeFinishedResponse) => void
  58. export type IOnIterationStarted = (workflowStarted: IterationStartedResponse) => void
  59. export type IOnIterationNext = (workflowStarted: IterationNextResponse) => void
  60. export type IOnIterationFinished = (workflowFinished: IterationFinishedResponse) => void
  61. export type IOnParallelBranchStarted = (parallelBranchStarted: ParallelBranchStartedResponse) => void
  62. export type IOnParallelBranchFinished = (parallelBranchFinished: ParallelBranchFinishedResponse) => void
  63. export type IOnTextChunk = (textChunk: TextChunkResponse) => void
  64. export type IOnTTSChunk = (messageId: string, audioStr: string, audioType?: string) => void
  65. export type IOnTTSEnd = (messageId: string, audioStr: string, audioType?: string) => void
  66. export type IOnTextReplace = (textReplace: TextReplaceResponse) => void
  67. export type IOtherOptions = {
  68. isPublicAPI?: boolean
  69. bodyStringify?: boolean
  70. needAllResponseContent?: boolean
  71. deleteContentType?: boolean
  72. silent?: boolean
  73. onData?: IOnData // for stream
  74. onThought?: IOnThought
  75. onFile?: IOnFile
  76. onMessageEnd?: IOnMessageEnd
  77. onMessageReplace?: IOnMessageReplace
  78. onError?: IOnError
  79. onCompleted?: IOnCompleted // for stream
  80. getAbortController?: (abortController: AbortController) => void
  81. onWorkflowStarted?: IOnWorkflowStarted
  82. onWorkflowFinished?: IOnWorkflowFinished
  83. onNodeStarted?: IOnNodeStarted
  84. onNodeFinished?: IOnNodeFinished
  85. onIterationStart?: IOnIterationStarted
  86. onIterationNext?: IOnIterationNext
  87. onIterationFinish?: IOnIterationFinished
  88. onParallelBranchStarted?: IOnParallelBranchStarted
  89. onParallelBranchFinished?: IOnParallelBranchFinished
  90. onTextChunk?: IOnTextChunk
  91. onTTSChunk?: IOnTTSChunk
  92. onTTSEnd?: IOnTTSEnd
  93. onTextReplace?: IOnTextReplace
  94. }
  95. type ResponseError = {
  96. code: string
  97. message: string
  98. status: number
  99. }
  100. type FetchOptionType = Omit<RequestInit, 'body'> & {
  101. params?: Record<string, any>
  102. body?: BodyInit | Record<string, any> | null
  103. }
  104. function unicodeToChar(text: string) {
  105. if (!text)
  106. return ''
  107. return text.replace(/\\u[0-9a-f]{4}/g, (_match, p1) => {
  108. return String.fromCharCode(parseInt(p1, 16))
  109. })
  110. }
  111. function requiredWebSSOLogin() {
  112. globalThis.location.href = `/webapp-signin?redirect_url=${globalThis.location.pathname}`
  113. }
  114. function getAccessToken(isPublicAPI?: boolean) {
  115. if (isPublicAPI) {
  116. const sharedToken = globalThis.location.pathname.split('/').slice(-1)[0]
  117. const accessToken = localStorage.getItem('token') || JSON.stringify({ [sharedToken]: '' })
  118. let accessTokenJson = { [sharedToken]: '' }
  119. try {
  120. accessTokenJson = JSON.parse(accessToken)
  121. }
  122. catch (e) {
  123. }
  124. return accessTokenJson[sharedToken]
  125. }
  126. else {
  127. return localStorage.getItem('console_token') || ''
  128. }
  129. }
  130. export function format(text: string) {
  131. let res = text.trim()
  132. if (res.startsWith('\n'))
  133. res = res.replace('\n', '')
  134. return res.replaceAll('\n', '<br/>').replaceAll('```', '')
  135. }
  136. const handleStream = (
  137. response: Response,
  138. onData: IOnData,
  139. onCompleted?: IOnCompleted,
  140. onThought?: IOnThought,
  141. onMessageEnd?: IOnMessageEnd,
  142. onMessageReplace?: IOnMessageReplace,
  143. onFile?: IOnFile,
  144. onWorkflowStarted?: IOnWorkflowStarted,
  145. onWorkflowFinished?: IOnWorkflowFinished,
  146. onNodeStarted?: IOnNodeStarted,
  147. onNodeFinished?: IOnNodeFinished,
  148. onIterationStart?: IOnIterationStarted,
  149. onIterationNext?: IOnIterationNext,
  150. onIterationFinish?: IOnIterationFinished,
  151. onParallelBranchStarted?: IOnParallelBranchStarted,
  152. onParallelBranchFinished?: IOnParallelBranchFinished,
  153. onTextChunk?: IOnTextChunk,
  154. onTTSChunk?: IOnTTSChunk,
  155. onTTSEnd?: IOnTTSEnd,
  156. onTextReplace?: IOnTextReplace,
  157. ) => {
  158. if (!response.ok)
  159. throw new Error('Network response was not ok')
  160. const reader = response.body?.getReader()
  161. const decoder = new TextDecoder('utf-8')
  162. let buffer = ''
  163. let bufferObj: Record<string, any>
  164. let isFirstMessage = true
  165. function read() {
  166. let hasError = false
  167. reader?.read().then((result: any) => {
  168. if (result.done) {
  169. onCompleted && onCompleted()
  170. return
  171. }
  172. buffer += decoder.decode(result.value, { stream: true })
  173. const lines = buffer.split('\n')
  174. try {
  175. lines.forEach((message) => {
  176. if (message.startsWith('data: ')) { // check if it starts with data:
  177. try {
  178. bufferObj = JSON.parse(message.substring(6)) as Record<string, any>// remove data: and parse as json
  179. }
  180. catch (e) {
  181. // mute handle message cut off
  182. onData('', isFirstMessage, {
  183. conversationId: bufferObj?.conversation_id,
  184. messageId: bufferObj?.message_id,
  185. })
  186. return
  187. }
  188. if (bufferObj.status === 400 || !bufferObj.event) {
  189. onData('', false, {
  190. conversationId: undefined,
  191. messageId: '',
  192. errorMessage: bufferObj?.message,
  193. errorCode: bufferObj?.code,
  194. })
  195. hasError = true
  196. onCompleted?.(true, bufferObj?.message)
  197. return
  198. }
  199. if (bufferObj.event === 'message' || bufferObj.event === 'agent_message') {
  200. // can not use format here. Because message is splitted.
  201. onData(unicodeToChar(bufferObj.answer), isFirstMessage, {
  202. conversationId: bufferObj.conversation_id,
  203. taskId: bufferObj.task_id,
  204. messageId: bufferObj.id,
  205. })
  206. isFirstMessage = false
  207. }
  208. else if (bufferObj.event === 'agent_thought') {
  209. onThought?.(bufferObj as ThoughtItem)
  210. }
  211. else if (bufferObj.event === 'message_file') {
  212. onFile?.(bufferObj as VisionFile)
  213. }
  214. else if (bufferObj.event === 'message_end') {
  215. onMessageEnd?.(bufferObj as MessageEnd)
  216. }
  217. else if (bufferObj.event === 'message_replace') {
  218. onMessageReplace?.(bufferObj as MessageReplace)
  219. }
  220. else if (bufferObj.event === 'workflow_started') {
  221. onWorkflowStarted?.(bufferObj as WorkflowStartedResponse)
  222. }
  223. else if (bufferObj.event === 'workflow_finished') {
  224. onWorkflowFinished?.(bufferObj as WorkflowFinishedResponse)
  225. }
  226. else if (bufferObj.event === 'node_started') {
  227. onNodeStarted?.(bufferObj as NodeStartedResponse)
  228. }
  229. else if (bufferObj.event === 'node_finished') {
  230. onNodeFinished?.(bufferObj as NodeFinishedResponse)
  231. }
  232. else if (bufferObj.event === 'iteration_started') {
  233. onIterationStart?.(bufferObj as IterationStartedResponse)
  234. }
  235. else if (bufferObj.event === 'iteration_next') {
  236. onIterationNext?.(bufferObj as IterationNextResponse)
  237. }
  238. else if (bufferObj.event === 'iteration_completed') {
  239. onIterationFinish?.(bufferObj as IterationFinishedResponse)
  240. }
  241. else if (bufferObj.event === 'parallel_branch_started') {
  242. onParallelBranchStarted?.(bufferObj as ParallelBranchStartedResponse)
  243. }
  244. else if (bufferObj.event === 'parallel_branch_finished') {
  245. onParallelBranchFinished?.(bufferObj as ParallelBranchFinishedResponse)
  246. }
  247. else if (bufferObj.event === 'text_chunk') {
  248. onTextChunk?.(bufferObj as TextChunkResponse)
  249. }
  250. else if (bufferObj.event === 'text_replace') {
  251. onTextReplace?.(bufferObj as TextReplaceResponse)
  252. }
  253. else if (bufferObj.event === 'tts_message') {
  254. onTTSChunk?.(bufferObj.message_id, bufferObj.audio, bufferObj.audio_type)
  255. }
  256. else if (bufferObj.event === 'tts_message_end') {
  257. onTTSEnd?.(bufferObj.message_id, bufferObj.audio)
  258. }
  259. }
  260. })
  261. buffer = lines[lines.length - 1]
  262. }
  263. catch (e) {
  264. onData('', false, {
  265. conversationId: undefined,
  266. messageId: '',
  267. errorMessage: `${e}`,
  268. })
  269. hasError = true
  270. onCompleted?.(true, e as string)
  271. return
  272. }
  273. if (!hasError)
  274. read()
  275. })
  276. }
  277. read()
  278. }
  279. const baseFetch = <T>(
  280. url: string,
  281. fetchOptions: FetchOptionType,
  282. {
  283. isPublicAPI = false,
  284. bodyStringify = true,
  285. needAllResponseContent,
  286. deleteContentType,
  287. getAbortController,
  288. silent,
  289. }: IOtherOptions,
  290. ): Promise<T> => {
  291. const options: typeof baseOptions & FetchOptionType = Object.assign({}, baseOptions, fetchOptions)
  292. if (getAbortController) {
  293. const abortController = new AbortController()
  294. getAbortController(abortController)
  295. options.signal = abortController.signal
  296. }
  297. const accessToken = getAccessToken(isPublicAPI)
  298. options.headers.set('Authorization', `Bearer ${accessToken}`)
  299. if (deleteContentType) {
  300. options.headers.delete('Content-Type')
  301. }
  302. else {
  303. const contentType = options.headers.get('Content-Type')
  304. if (!contentType)
  305. options.headers.set('Content-Type', ContentType.json)
  306. }
  307. const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
  308. let urlWithPrefix = (url.startsWith('http://') || url.startsWith('https://'))
  309. ? url
  310. : `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`
  311. const { method, params, body } = options
  312. // handle query
  313. if (method === 'GET' && params) {
  314. const paramsArray: string[] = []
  315. Object.keys(params).forEach(key =>
  316. paramsArray.push(`${key}=${encodeURIComponent(params[key])}`),
  317. )
  318. if (urlWithPrefix.search(/\?/) === -1)
  319. urlWithPrefix += `?${paramsArray.join('&')}`
  320. else
  321. urlWithPrefix += `&${paramsArray.join('&')}`
  322. delete options.params
  323. }
  324. if (body && bodyStringify)
  325. options.body = JSON.stringify(body)
  326. // Handle timeout
  327. return Promise.race([
  328. new Promise((resolve, reject) => {
  329. setTimeout(() => {
  330. reject(new Error('request timeout'))
  331. }, TIME_OUT)
  332. }),
  333. new Promise((resolve, reject) => {
  334. globalThis.fetch(urlWithPrefix, options as RequestInit)
  335. .then((res) => {
  336. const resClone = res.clone()
  337. // Error handler
  338. if (!/^(2|3)\d{2}$/.test(String(res.status))) {
  339. const bodyJson = res.json()
  340. switch (res.status) {
  341. case 401:
  342. return Promise.reject(resClone)
  343. case 403:
  344. bodyJson.then((data: ResponseError) => {
  345. if (!silent)
  346. Toast.notify({ type: 'error', message: data.message })
  347. if (data.code === 'already_setup')
  348. globalThis.location.href = `${globalThis.location.origin}/signin`
  349. })
  350. break
  351. // fall through
  352. default:
  353. bodyJson.then((data: ResponseError) => {
  354. if (!silent)
  355. Toast.notify({ type: 'error', message: data.message })
  356. })
  357. }
  358. return Promise.reject(resClone)
  359. }
  360. // handle delete api. Delete api not return content.
  361. if (res.status === 204) {
  362. resolve({ result: 'success' })
  363. return
  364. }
  365. // return data
  366. if (options.headers.get('Content-type') === ContentType.download || options.headers.get('Content-type') === ContentType.audio)
  367. resolve(needAllResponseContent ? resClone : res.blob())
  368. else resolve(needAllResponseContent ? resClone : res.json())
  369. })
  370. .catch((err) => {
  371. if (!silent)
  372. Toast.notify({ type: 'error', message: err })
  373. reject(err)
  374. })
  375. }),
  376. ]) as Promise<T>
  377. }
  378. export const upload = (options: any, isPublicAPI?: boolean, url?: string, searchParams?: string): Promise<any> => {
  379. const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
  380. const token = getAccessToken(isPublicAPI)
  381. const defaultOptions = {
  382. method: 'POST',
  383. url: (url ? `${urlPrefix}${url}` : `${urlPrefix}/files/upload`) + (searchParams || ''),
  384. headers: {
  385. Authorization: `Bearer ${token}`,
  386. },
  387. data: {},
  388. }
  389. options = {
  390. ...defaultOptions,
  391. ...options,
  392. headers: { ...defaultOptions.headers, ...options.headers },
  393. }
  394. return new Promise((resolve, reject) => {
  395. const xhr = options.xhr
  396. xhr.open(options.method, options.url)
  397. for (const key in options.headers)
  398. xhr.setRequestHeader(key, options.headers[key])
  399. xhr.withCredentials = true
  400. xhr.responseType = 'json'
  401. xhr.onreadystatechange = function () {
  402. if (xhr.readyState === 4) {
  403. if (xhr.status === 201)
  404. resolve(xhr.response)
  405. else
  406. reject(xhr)
  407. }
  408. }
  409. xhr.upload.onprogress = options.onprogress
  410. xhr.send(options.data)
  411. })
  412. }
  413. export const ssePost = (
  414. url: string,
  415. fetchOptions: FetchOptionType,
  416. otherOptions: IOtherOptions,
  417. ) => {
  418. const {
  419. isPublicAPI = false,
  420. onData,
  421. onCompleted,
  422. onThought,
  423. onFile,
  424. onMessageEnd,
  425. onMessageReplace,
  426. onWorkflowStarted,
  427. onWorkflowFinished,
  428. onNodeStarted,
  429. onNodeFinished,
  430. onIterationStart,
  431. onIterationNext,
  432. onIterationFinish,
  433. onParallelBranchStarted,
  434. onParallelBranchFinished,
  435. onTextChunk,
  436. onTTSChunk,
  437. onTTSEnd,
  438. onTextReplace,
  439. onError,
  440. getAbortController,
  441. } = otherOptions
  442. const abortController = new AbortController()
  443. const options = Object.assign({}, baseOptions, {
  444. method: 'POST',
  445. signal: abortController.signal,
  446. }, fetchOptions)
  447. const contentType = options.headers.get('Content-Type')
  448. if (!contentType)
  449. options.headers.set('Content-Type', ContentType.json)
  450. getAbortController?.(abortController)
  451. const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
  452. const urlWithPrefix = (url.startsWith('http://') || url.startsWith('https://'))
  453. ? url
  454. : `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`
  455. const { body } = options
  456. if (body)
  457. options.body = JSON.stringify(body)
  458. const accessToken = getAccessToken(isPublicAPI)
  459. options.headers.set('Authorization', `Bearer ${accessToken}`)
  460. globalThis.fetch(urlWithPrefix, options as RequestInit)
  461. .then((res) => {
  462. if (!/^(2|3)\d{2}$/.test(String(res.status))) {
  463. if (res.status === 401) {
  464. refreshAccessTokenOrRelogin(TIME_OUT).then(() => {
  465. ssePost(url, fetchOptions, otherOptions)
  466. }).catch(() => {
  467. res.json().then((data: any) => {
  468. if (isPublicAPI) {
  469. if (data.code === 'web_sso_auth_required')
  470. requiredWebSSOLogin()
  471. if (data.code === 'unauthorized') {
  472. removeAccessToken()
  473. globalThis.location.reload()
  474. }
  475. }
  476. })
  477. })
  478. }
  479. else {
  480. res.json().then((data) => {
  481. Toast.notify({ type: 'error', message: data.message || 'Server Error' })
  482. })
  483. onError?.('Server Error')
  484. }
  485. return
  486. }
  487. return handleStream(res, (str: string, isFirstMessage: boolean, moreInfo: IOnDataMoreInfo) => {
  488. if (moreInfo.errorMessage) {
  489. onError?.(moreInfo.errorMessage, moreInfo.errorCode)
  490. // TypeError: Cannot assign to read only property ... will happen in page leave, so it should be ignored.
  491. if (moreInfo.errorMessage !== 'AbortError: The user aborted a request.' && !moreInfo.errorMessage.includes('TypeError: Cannot assign to read only property'))
  492. Toast.notify({ type: 'error', message: moreInfo.errorMessage })
  493. return
  494. }
  495. onData?.(str, isFirstMessage, moreInfo)
  496. }, onCompleted, onThought, onMessageEnd, onMessageReplace, onFile, onWorkflowStarted, onWorkflowFinished, onNodeStarted, onNodeFinished, onIterationStart, onIterationNext, onIterationFinish, onParallelBranchStarted, onParallelBranchFinished, onTextChunk, onTTSChunk, onTTSEnd, onTextReplace)
  497. }).catch((e) => {
  498. if (e.toString() !== 'AbortError: The user aborted a request.' && !e.toString().errorMessage.includes('TypeError: Cannot assign to read only property'))
  499. Toast.notify({ type: 'error', message: e })
  500. onError?.(e)
  501. })
  502. }
  503. // base request
  504. export const request = async<T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  505. try {
  506. const otherOptionsForBaseFetch = otherOptions || {}
  507. const [err, resp] = await asyncRunSafe<T>(baseFetch(url, options, otherOptionsForBaseFetch))
  508. if (err === null)
  509. return resp
  510. const errResp: Response = err as any
  511. if (errResp.status === 401) {
  512. const [parseErr, errRespData] = await asyncRunSafe<ResponseError>(errResp.json())
  513. const loginUrl = `${globalThis.location.origin}/signin`
  514. if (parseErr) {
  515. globalThis.location.href = loginUrl
  516. return Promise.reject(err)
  517. }
  518. // special code
  519. const { code, message } = errRespData
  520. // webapp sso
  521. if (code === 'web_sso_auth_required') {
  522. requiredWebSSOLogin()
  523. return Promise.reject(err)
  524. }
  525. if (code === 'unauthorized_and_force_logout') {
  526. localStorage.removeItem('console_token')
  527. localStorage.removeItem('refresh_token')
  528. globalThis.location.reload()
  529. return Promise.reject(err)
  530. }
  531. const {
  532. isPublicAPI = false,
  533. silent,
  534. } = otherOptionsForBaseFetch
  535. if (isPublicAPI && code === 'unauthorized') {
  536. removeAccessToken()
  537. globalThis.location.reload()
  538. return Promise.reject(err)
  539. }
  540. if (code === 'init_validate_failed' && IS_CE_EDITION && !silent) {
  541. Toast.notify({ type: 'error', message, duration: 4000 })
  542. return Promise.reject(err)
  543. }
  544. if (code === 'not_init_validated' && IS_CE_EDITION) {
  545. globalThis.location.href = `${globalThis.location.origin}/init`
  546. return Promise.reject(err)
  547. }
  548. if (code === 'not_setup' && IS_CE_EDITION) {
  549. globalThis.location.href = `${globalThis.location.origin}/install`
  550. return Promise.reject(err)
  551. }
  552. // refresh token
  553. const [refreshErr] = await asyncRunSafe(refreshAccessTokenOrRelogin(TIME_OUT))
  554. if (refreshErr === null)
  555. return baseFetch<T>(url, options, otherOptionsForBaseFetch)
  556. if (location.pathname !== '/signin' || !IS_CE_EDITION) {
  557. globalThis.location.href = loginUrl
  558. return Promise.reject(err)
  559. }
  560. if (!silent) {
  561. Toast.notify({ type: 'error', message })
  562. return Promise.reject(err)
  563. }
  564. globalThis.location.href = loginUrl
  565. return Promise.reject(err)
  566. }
  567. else {
  568. return Promise.reject(err)
  569. }
  570. }
  571. catch (error) {
  572. console.error(error)
  573. return Promise.reject(error)
  574. }
  575. }
  576. // request methods
  577. export const get = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  578. return request<T>(url, Object.assign({}, options, { method: 'GET' }), otherOptions)
  579. }
  580. // For public API
  581. export const getPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  582. return get<T>(url, options, { ...otherOptions, isPublicAPI: true })
  583. }
  584. export const post = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  585. return request<T>(url, Object.assign({}, options, { method: 'POST' }), otherOptions)
  586. }
  587. export const postPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  588. return post<T>(url, options, { ...otherOptions, isPublicAPI: true })
  589. }
  590. export const put = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  591. return request<T>(url, Object.assign({}, options, { method: 'PUT' }), otherOptions)
  592. }
  593. export const putPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  594. return put<T>(url, options, { ...otherOptions, isPublicAPI: true })
  595. }
  596. export const del = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  597. return request<T>(url, Object.assign({}, options, { method: 'DELETE' }), otherOptions)
  598. }
  599. export const delPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  600. return del<T>(url, options, { ...otherOptions, isPublicAPI: true })
  601. }
  602. export const patch = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  603. return request<T>(url, Object.assign({}, options, { method: 'PATCH' }), otherOptions)
  604. }
  605. export const patchPublic = <T>(url: string, options = {}, otherOptions?: IOtherOptions) => {
  606. return patch<T>(url, options, { ...otherOptions, isPublicAPI: true })
  607. }