refactor: 优化去背景工具代码,消除文件内部重复

- 在文件内部提取 handleSuccess 辅助函数,消除成功处理逻辑重复
- 简化流式响应处理代码,提高可读性和可维护性
- 保持工具文件独立性,符合设计原则
This commit is contained in:
jingrow 2026-01-02 20:23:02 +08:00
parent 6b638ac143
commit 8f141188a3
2 changed files with 52 additions and 87 deletions

View File

@ -517,11 +517,30 @@ const handleRemoveBackground = async () => {
processing.value = true
resultImage.value = ''
// 使
const handleSuccess = async (imageUrl: string): Promise<void> => {
resultImage.value = imageUrl
await cacheResultImage(imageUrl)
if (currentHistoryIndex.value === -1 && uploadedImage.value && uploadedImageUrl.value) {
const historyItem: HistoryItem = {
id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
originalImageUrl: uploadedImageUrl.value,
originalImageFile: uploadedImage.value,
resultImage: imageUrl,
timestamp: Date.now()
}
historyList.value.unshift(historyItem)
currentHistoryIndex.value = 0
} else if (currentHistoryIndex.value >= 0) {
historyList.value[currentHistoryIndex.value].resultImage = imageUrl
}
}
try {
const formData = new FormData()
formData.append('file', uploadedImage.value)
// 使 fetch NDJSON
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), 180000)
@ -537,7 +556,6 @@ const handleRemoveBackground = async () => {
throw new Error(`HTTP error! status: ${response.status}`)
}
// NDJSON JSON
const reader = response.body?.getReader()
const decoder = new TextDecoder()
let buffer = ''
@ -552,38 +570,17 @@ const handleRemoveBackground = async () => {
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() || '' //
buffer = lines.pop() || ''
//
for (const line of lines) {
if (line.trim()) {
try {
const result = JSON.parse(line.trim())
// {"status": "success", "image_url": "..."}
if (result.status === 'success' && result.image_url) {
resultImage.value = result.image_url
// blob URL
await cacheResultImage(result.image_url)
//
if (currentHistoryIndex.value === -1 && uploadedImage.value && uploadedImageUrl.value) {
const historyItem: HistoryItem = {
id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
originalImageUrl: uploadedImageUrl.value,
originalImageFile: uploadedImage.value,
resultImage: result.image_url,
timestamp: Date.now()
}
historyList.value.unshift(historyItem)
currentHistoryIndex.value = 0
} else if (currentHistoryIndex.value >= 0) {
historyList.value[currentHistoryIndex.value].resultImage = result.image_url
}
return // 退
} else {
message.error(result.error || t('Failed to remove background'))
await handleSuccess(result.image_url)
return
} else if (result.error) {
message.error(result.error)
}
} catch (parseError) {
console.error('Failed to parse JSON:', parseError, 'Line:', line)
@ -597,22 +594,7 @@ const handleRemoveBackground = async () => {
try {
const result = JSON.parse(buffer.trim())
if (result.status === 'success' && result.image_url) {
resultImage.value = result.image_url
await cacheResultImage(result.image_url)
if (currentHistoryIndex.value === -1 && uploadedImage.value && uploadedImageUrl.value) {
const historyItem: HistoryItem = {
id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
originalImageUrl: uploadedImageUrl.value,
originalImageFile: uploadedImage.value,
resultImage: result.image_url,
timestamp: Date.now()
}
historyList.value.unshift(historyItem)
currentHistoryIndex.value = 0
} else if (currentHistoryIndex.value >= 0) {
historyList.value[currentHistoryIndex.value].resultImage = result.image_url
}
await handleSuccess(result.image_url)
return
} else {
message.error(result.error || t('Failed to remove background'))

View File

@ -608,11 +608,30 @@ const handleRemoveBackground = async () => {
processing.value = true
resultImage.value = ''
// 使
const handleSuccess = async (imageUrl: string): Promise<void> => {
resultImage.value = imageUrl
await cacheResultImage(imageUrl)
if (currentHistoryIndex.value === -1 && uploadedImage.value && uploadedImageUrl.value) {
const historyItem: HistoryItem = {
id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
originalImageUrl: uploadedImageUrl.value,
originalImageFile: uploadedImage.value,
resultImage: imageUrl,
timestamp: Date.now()
}
historyList.value.unshift(historyItem)
currentHistoryIndex.value = 0
} else if (currentHistoryIndex.value >= 0) {
historyList.value[currentHistoryIndex.value].resultImage = imageUrl
}
}
try {
const formData = new FormData()
formData.append('file', uploadedImage.value)
// 使 fetch NDJSON
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), 180000)
@ -628,7 +647,6 @@ const handleRemoveBackground = async () => {
throw new Error(`HTTP error! status: ${response.status}`)
}
// NDJSON JSON
const reader = response.body?.getReader()
const decoder = new TextDecoder()
let buffer = ''
@ -643,37 +661,17 @@ const handleRemoveBackground = async () => {
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() || '' //
buffer = lines.pop() || ''
//
for (const line of lines) {
if (line.trim()) {
try {
const result = JSON.parse(line.trim())
// {"status": "success", "image_url": "..."}
if (result.status === 'success' && result.image_url) {
resultImage.value = result.image_url
// blob URL
await cacheResultImage(result.image_url)
if (currentHistoryIndex.value === -1 && uploadedImage.value && uploadedImageUrl.value) {
const historyItem: HistoryItem = {
id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
originalImageUrl: uploadedImageUrl.value,
originalImageFile: uploadedImage.value,
resultImage: result.image_url,
timestamp: Date.now()
}
historyList.value.unshift(historyItem)
currentHistoryIndex.value = 0
} else if (currentHistoryIndex.value >= 0) {
historyList.value[currentHistoryIndex.value].resultImage = result.image_url
}
return // 退
} else {
message.error(result.error || t('Failed to remove background'))
await handleSuccess(result.image_url)
return
} else if (result.error) {
message.error(result.error)
}
} catch (parseError) {
console.error('Failed to parse JSON:', parseError, 'Line:', line)
@ -687,22 +685,7 @@ const handleRemoveBackground = async () => {
try {
const result = JSON.parse(buffer.trim())
if (result.status === 'success' && result.image_url) {
resultImage.value = result.image_url
await cacheResultImage(result.image_url)
if (currentHistoryIndex.value === -1 && uploadedImage.value && uploadedImageUrl.value) {
const historyItem: HistoryItem = {
id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
originalImageUrl: uploadedImageUrl.value,
originalImageFile: uploadedImage.value,
resultImage: result.image_url,
timestamp: Date.now()
}
historyList.value.unshift(historyItem)
currentHistoryIndex.value = 0
} else if (currentHistoryIndex.value >= 0) {
historyList.value[currentHistoryIndex.value].resultImage = result.image_url
}
await handleSuccess(result.image_url)
return
} else {
message.error(result.error || t('Failed to remove background'))